PDA

View Full Version : Resolved JQuery Ajax - Posting to Database



Deadweight
12-06-2013, 07:34 PM
The problem isn't with the php nor posting to the database. It's what I have to do to post to the database.

It works with this code:

$("#sub").click( function() {
$.ajax({
type: "POST",
url: "userInfo.php",
data: $("#myForm").serializeArray(),
success: function(data){
alert("Win");
}
});
alert("Your data has been saved!");
});

DOESNT work with this code:

$("#sub").click( function() {
$.ajax({
type: "POST",
url: "userInfo.php",
data: $("#myForm").serializeArray(),
success: function(data){
alert("Win");
}
});
//alert("Your data has been saved!");
});

Any reasons why that's happening?

jscheuer1
12-06-2013, 08:32 PM
Technically speaking, unless I missed something, there's no difference between those two except the 2nd alert is commented out in the second example. However, there's much I cannot see. I can see that this code does not prevent the default action of the form. So perhaps the form is submitting in one or the other of the cases or in both cases but in different sequence thus changing the overall result.

Generally when we wish to pass POST data to a PHP script, we .serialize() the form data, not .serializeArray() it. That might have something to do with it. Try:


$("#sub").click( function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "userInfo.php",
data: $("#myForm").serialize(),
success: function(data){
alert("Win");
}
});
//alert("Your data has been saved!");
});

The browser cache may need to be cleared and/or the page refreshed to see changes.

If you want more help, please include a link to the page on your site that contains the problematic code so we can check it out.

Deadweight
12-06-2013, 11:05 PM
That actually fixed the problem. It didn't matter which serialize i used.
Can you explain what preventDefault does?

jscheuer1
12-07-2013, 02:10 AM
In this case it stops the default action of the event (e) that occurs whenever there is a click on the element with the id of sub. Like, if that would have submitted the form in the normal fashion, that's prevented. Or if it would have navigated to another page, that's prevented, etc.

I can't be any more specific without seeing the page.

See also:

http://api.jquery.com/event.preventDefault/