6

I'm still new to JQuery, AJAX and PHP.

I was wondering what I could be doing wrong here. I am taking in information about a customer and trying to return a confirmation message on the same page.

So the problems I am having: 1) Clicking on the submit button refreshes my page? Why?

2) I have a underneath my submit button. How would I be able to change the text of that with the results of addCustomer.php?

3) Is it okay to have my javascript and php code in the same file under customer.php?

Edit: Also I am using Firefox's Tamper Data Addon - when I click submit, no data is sent for some reason.

Customer.php

<script type="text/javascript">

$(document).ready(function(){
    $('#submit').click(function() {
        $.ajax({
            type : 'POST',
            url : 'addCustomer.php',
            dataType : 'json',
            data:{
                add_LN : $('#add_LN').val(),
                add_FN : $('#add_FN').val(),
                add_PN : $('#add_PN').val(),
                add_DOB : $('#add_DOB').val()
            },
            success : function(data){
                //I want to change the "confirmMsg" to the string given back from addCustomer.php
            }
        }
    }
}

</script>

<p>&nbsp;</p>
<p>Add New Customer:</p>
<div align="center">
<form>
  <table width="396" border="1">
    <tr>
      <td width="133"><p>Last Name:</p>
      <p>First Name:</p>
      <p>Phone Number:</p>
      <p>Date of Birth:</p></td>
      <td width="144"><p>
        <input type="text" name="add_LN" id="add_LN" />
        </p>
      <p>
        <input type="text" name="add_FN" id="add_FN" />
        </p>
      <p>
        <input type="text" name="add_PN" id="add_PN" />
        </p>
      <p>
        <input type="text" name="add_DOB" id="add_DOB" />
      </p>        </td>
      <td width="97"><input type="submit" name="submit" id="submit" value="Add Customer" /></td>
      <div id="confirmMsg"/>
        </tr>
      </table>
    </form>
  </div>
<p>&nbsp;</p>
</div>
</div>

addCustomer.php

<?php
$username="******";
$password="******";
$database="******";

if (isset ($_POST['add_LN']))
    $lastName=$_POST['add_LN'];
else
    die("Last Name not passed in POST");

if (isset ($_POST['add_FN']))
    $firstName=$_POST['add_FN'];
else
    die ("First Name not passed in POST");

if (isset ( $_POST['add_PN']))
    $phone=$_POST['add_PN'];
else
    die("Phone Number not passed in POST");

if (isset ($_POST['add_DOB']))
    $dob=$_POST['add_DOB'];
else
    die("Date of Birth not passed in Post");

//$membership==$_POST['membership'];

mysql_connect("dbs4.cpsc.u.ca",$username,$password);

@mysql_select_db($database) or die( "Unable to select database");


$query = "INSERT INTO customer (last_name, first_name, phone_no, date_of_birth, membership) VALUES ('$lastName', '$firstName', '$phone', '$dob', 'T')";

if (mysql_query($query)){
    echo "Thanks";
} else 
{
    echo "Failed to insert customer into database";
}

mysql_close();
?>

Thanks so much for the help!

4
  • You could try to check if the form gets posted using firebug (if you're using firefox) or the chrome developer tools to start with Commented Apr 10, 2011 at 20:12
  • Your html code isn't right, the confirmMsg div is placed outside your table cell, this isn't supposed to work, but you shouldn't be placing your form in a table to start with. If you place your form inside a form tag you could listen to the submit handler with jquery. Commented Apr 10, 2011 at 20:19
  • I'm currently using Tamper Data for firefox but it isn't picking up anything when I hit submit. Also, why should I not put the form in a table? It should still work the same. Edit - woops i didnt realize that it wasn't in a form thanks. I reverted my code back without realizing. Sorry :P Commented Apr 10, 2011 at 20:25
  • try this stackoverflow.com/questions/19029703/… Commented Sep 26, 2013 at 16:20

4 Answers 4

2

Ok, to answer your questions in order:

  1. You should be able to check from Firebug (you are using Firebug, right?) in the Console tab to see that addCustomer.php is the endpoint being called by your Ajax request. Failing that, you can add the following code into your scripts:

    $('#confirmMsg').ajaxComplete(function(e, xhr, settings) {
        $(this).text('The response from your page is ' + xhr.responseHTML);
    });
    
  2. I'm assuming that your question here is "I have a div underneath my submit button...". Try the following command (which is a shortened version of the full Ajax method):

    $.post('addCustomer.php', {
        add_LN : $('#add_LN').val(),
        add_FN : $('#add_FN').val(),
        add_PN : $('#add_PN').val(),
        add_DOB : $('#add_DOB').val()
    }, function(data){
        $('#confirmMsg').text(data);
    });
    
  3. Finally, yes - it is ok to have your script and PHP code on the same page. The PHP code is executed on the server before being rendered to your browser and the JavaScript works on the client side, executing once the page is delivered.

Sign up to request clarification or add additional context in comments.

10 Comments

Hey! WHat happened to the code markdown for the answer?! :-(
Code inside lists needs 4 more spaces. I edited it. See also meta.stackexchange.com/questions/3792/…
For your answer to number one, where should that go? Should I have that inside succes(function()? As well as #2 Sorry I am very new to this! :) Thanks so much for spending the time to answer my questions
@Aero That code is a separate method that can sit outside your Ajax call. It's an event handler that basically listens for any Ajax method and, once that method has finished, AjaxComplete will then execute. read more on the jQuery API documentation.
Also, after placing the form tags around my table, when I click submit, my page refreshes for some reason... Also in the tag for <script type="text/javascript", ive also included src='jquery.js' I have also included the file in the same folder. Is it always necessary for AJAX to work?
|
1

1) you can use the "preventDefault" on the click function. 2) you can add a success message by just displaying the "confirmMsg" div (hide it first with css) 3) if thats works for you it's oke. but i self try to keep all the code just on one place eg. "main.js"

See the code: ^my changes^ "just remove the ^ to make it work :)"

<script type="text/javascript">

$(document).ready(function(){
    $('#submit').click(function(^e^) {
        ^e.preventDefault();^
        $.ajax({
            type : 'POST',
            url : 'addCustomer.php',
            ^data: $('form').serializeArray(),^
            success : function(data){
                ^$('#confirmMsg').show();^
            }
        }
    }
}

</script>

I think this should do the trick :) I've added the serializeArray function to make it more dynamic because if you have more input fields you don't have to change the js code again. http://api.jquery.com/serializeArray/

You can see what the form sends to first open firebug and reload the page then field the fields then submit it. You will see in the "console" tab some change ;)

I hope this will help you out.

2 Comments

I have tried e.preventDefault, but it still refreshes unfortunately. Any other suggestions?
Darn, firebug doesn't show anything for me in console except: Issues with trunk Firefox for Firebug: getfirebug.com/knownissues
0

I suggest you change dataType: 'json' to dataType: 'text', that might be what's tripping jQuery up.

And change your success handler to

success: function(data){
    $("#confirmMsg").html(data);
}

Comments

0

Problem was the was not in the head of that file. It fixed all my problems but not sure why. Thanks to everyone who contributed

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<style type="text/css">
</style>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#submit').click(function(e) {
        $.ajax({
            type : 'POST',
            url : 'addCustomer.php',
            dataType : 'json',
            data:{
                lastName : $('#add_LN').val(),
                firstName : $('#add_FN').val(),
                phone : $('#add_PN').val(),
                dob : $('#add_DOB').val()
            },
            success : function(data){
                if (data.error === true){
                    alert("there was an error in the post layer");
                } else {
                    $('#confirmMsg').html(data);
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
        return false;
    });
});
</script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.