Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX - Sending data to my php file does not seem to work [duplicate]

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!

like image 662
Aero Chocolate Avatar asked Apr 10 '11 20:04

Aero Chocolate


2 Answers

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.

like image 196
Phil.Wheeler Avatar answered Oct 30 '22 17:10

Phil.Wheeler


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.

like image 44
Aphichat Avatar answered Oct 30 '22 18:10

Aphichat