Reputation: 1140
I have tried many times with jQuery ajax call but it return value before updating it. i have googled it and tried lots of solutions no one work for me, i always get undefined value because function return value before ajax call complete. any help would be appreciate,
here is my code
$(document).ready(function() {
console.log(secondvalidation());
});
function onemorevalid() {
console.log("working");
//this ajax call return 1
return jQuery.ajax({
url: 'handler/email.php',
method: 'POST',
});
}
function secondvalidation() {
onemorevalid1 = new onemorevalid();
onemorevalid1.done(function(data) {
console.log("data " + data);
return data;
});
}
output on console is
working
undefined
data 1
Upvotes: 0
Views: 294
Reputation: 2442
You're making an object out of a method. Which is wrong fundamentally. Also if you need to pass the value of an ajax call to code called afterwards, you can add async:false
to you query so that the code will wait for the ajax response.
Just make sure that you call the other_function()
after the ajax method gets called in document ready function.
So I think what you need is this:
$(document).ready(function(){
var requested_data;
var request = $.ajax({
url:'handler/email.php',
method:'POST',
async:false,
dataType: 'text'
});
request.done(function(data) {
console.log("data " + data);
requested_data = data
});
function other_function(){
console.log("toing_toing: " + requested_data);
}
other_function();
});
here's a working example fiddle of this code.
Please note that there are other ways to achieve this as per this answer. async:false
may cause your script to freeze till the request is complete, and thus if the request took a long time that would give a bad UI experience.
Upvotes: 1