Reputation: 612
I want to submit my form using ajax.
Below is my code:
$("#loginForm").submit(function() {
var url = <url>;
$.ajax({
type: "POST",
url: url,
data: $("#loginForm").serialize(), // serializes the form's elements.
success: function(data)
{
if(data == '0'){
$("#loginErr").show();
return false;
}
else if(data == '1')
return true;
}
});
return false;
});
I want to get my form submitted if ajax response is 1. but irrespective of data value, form is not getting submitted. Its always getting return value false. I have checked it reaches to else if condition, but execution is not stopped on return.
How can I submit my form? I want to refresh my page.
Upvotes: 0
Views: 318
Reputation: 612
As I wanted to refresh my page, I did want synchronous request. Setting async false solved the issue. I am able to get ret value outside Ajax object as it is requested synchronously.
$("#loginForm").submit(function() {
var url = <url>;
var ret = false;
$.ajax({
async: false,
type: "POST",
url: url,
data: $("#loginForm").serialize(), // serializes the form's elements.
success: function(data)
{
//alert(data); // show response from the php script.
if(data == '1')
ret = true;
else if(data == '0')
$("#loginErr").show();
}
});
return ret;
});
Upvotes: 0
Reputation: 349
I am not sure which data you would like checked. But if this data comes from the form itself, then you need to check it before ajax call. Once you make the ajax post call, your form is already submitted.
$("#loginForm").submit(function(e)
{
var url = <url>;
e.preventDefault();
mydata = $("#loginForm").serialize();
//Your check here
if(mydata == '0')
{
$("#loginErr").show();
return false;
}
$.ajax({
type: "POST",
url: url,
data: mydata,
success: function(response)
{
//this is your post response processor
}
});
return false;
});
Upvotes: 0
Reputation: 74420
Use that:
$("#loginForm").submit(function (event) {
var url = < url > ;
$.ajax({
type: "POST",
url: url,
context:this, //setting context on form
data: $("#loginForm").serialize(), // serializes the form's elements.
success: function (data) {
if (data == '0') $("#loginErr").show();
else if (data == '1') this.submit();//use js submit event, not jq. We need to manually submit it now that we know its successful
}
});
event.preventDefault(); //Stop the form submitting straight away
});
Upvotes: 1