Trouble with jQuery form submit
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?
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
});
});
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;
});
});
精彩评论