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!

Aero Chocolate
  • 1,477
  • 6
  • 23
  • 39
  • 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 – Han Dijk Apr 10 '11 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. – Han Dijk Apr 10 '11 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 – Aero Chocolate Apr 10 '11 at 20:25
  • try this http://stackoverflow.com/questions/19029703/jquery-using-ajax-to-send-data-and-save-in-php/19029778#19029778 – rohitcopyright Sep 26 '13 at 16:20

4 Answers4

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Phil.Wheeler
  • 16,748
  • 10
  • 99
  • 155
  • Hey! WHat happened to the code markdown for the answer?! :-( – Phil.Wheeler Apr 10 '11 at 20:30
  • Code inside lists needs 4 more spaces. I edited it. See also http://meta.stackexchange.com/questions/3792/how-to-nest-code-within-a-list-using-markdown – BalusC Apr 10 '11 at 20:33
  • 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 Chocolate Apr 10 '11 at 20:38
  • @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](http://api.jquery.com/ajax/ajaxcomplete). – Phil.Wheeler Apr 10 '11 at 20:39
  • Also, after placing the form tags around my table, when I click submit, my page refreshes for some reason... Also in the tag for – Aero Chocolate Apr 10 '11 at 20:39
  • Well you don't technically need a "Submit" input to submit an Ajax form. Try changing it to an actual button: ``. Your script file can be anywhere you want as long as you've referenced it correctly. – Phil.Wheeler Apr 10 '11 at 20:52
  • Alternatively, to stop the page refreshing, you need to stop the postback that happens with HTML forms by default. Because you have a `
    ` tag on your page, the browser will try to submit that form when you click a "Submit" button. To avoid this, add `return false;` to the end of your submit click event handler.
    – Phil.Wheeler Apr 10 '11 at 20:53
  • So I have changed: $(document).ready(function(){ $('#submit'),click(function(e){ ... return false; } Still refreshes unfortunately, any other suggestions? – Aero Chocolate Apr 10 '11 at 21:13
  • I have also tried the button, but it still refreshes. This problem is so odd haha – Aero Chocolate Apr 10 '11 at 21:19
  • Let's step back for a sec. Can you paste all your HTML in so we can see the problem a bit more clearly? – Phil.Wheeler Apr 10 '11 at 21:21
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.

Aphichat
  • 11
  • 1
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);
}
mattsven
  • 22,305
  • 11
  • 68
  • 104
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>
Aero Chocolate
  • 1,477
  • 6
  • 23
  • 39