tags:

views:

34

answers:

2

I am at a loss here with some simple jQuery. I have the following code in a separate file:

 $(document).ready(function(){
    //$("#trackit").click(function() {  

    $.ajax({
       type: "POST",
       url: 'include/trackit.php',
       data: "trackingNum=123456",
       success: function(data) {
         alert(data);
       }
    });

   //});  
});

That works just fine, on page load it returns the expected data to the alert window.

But, if I remove the comments from this line:

$("#trackit").click(function() { 

to capture the form's submit button, I get no return data.

Here is the abbreviated form info:

<form action="<?php htmlentities($_SERVER['PHP_SELF']);?>" name="tForm" id="tForm" method="post">

    <button type="submit" class="buttonTracking" id="trackit" name="trackit">Track It!</button>

</form>

Am I just overlooking some simple error here?

+3  A: 

Correct working code would be this:

 $(document).ready(function(){
    $("#trackit").click(function() {  

    $.ajax({
       type: "POST",
       url: 'include/trackit.php',
       data: "trackingNum=123456",
       success: function(data) {
         alert(data);
       }
    });
    return false; // to cancel form submission and subsequent page refresh
   });  
});
Andrew Kolesnikov
Bingo, that did the trick! Thank you very much!
Dave
+1  A: 

I'd say it's because the #trackit button is also a submit button. The click action is executing your javascript AND submitting the form. You need to change the code to:

$(document).ready(function(){
  $("#trackit").click(function() {  

  $.ajax({
    type: "POST",
    url: 'include/trackit.php',
    data: "trackingNum=123456",
    success: function(data) {
      alert(data);
    }
  });
  return false;
 });  
});
Ben Rowe