Get the variable after ajax when done

$('#submit_id').click(function(){ function mark() { $.ajax({ type: "POST", url: "request1.php", data: $('#form_id').serialize(), cache: false, success: function(data1){ } }); } function other() { $.ajax({ type: "POST", url: "request2.php", data: $('#form_id').serialize(), cache: false, success: function(data2){ } }); } $.when(mark(), other()).done(function(data1, data2) { console.log(data1); $(".results1").html(data1); console.log(data2); // Result $(".results2").html(data2); }); }); 

I need to pass the returned data to a type variable:

Console

: undefined

+4
source share
3 answers

Your code should work as follows:

 $.when(mark(), other()).done(function(data1, data2){ console.log(data1); $(".results1").html(data1); console.log(data2); // Result $(".results2").html(data2); }); function mark() { return $.ajax({ type: "POST", url: "request1.php", data: $('#form_id').serialize(), cache: false }); } function other() { return $.ajax({ type: "POST", url: "request2.php", data: $('#form_id').serialize(), cache: false }); } 
+1
source

You should return the promise interface from your functions as:

 function mark() { return $.ajax({ type: "POST", url: "request1.php", data: $('#form_id').serialize(), cache: false }); } 

And you don't need to specify a success callback here (but you can still).

+4
source

try it

 $('#submit_id').click(function(){ function mark() { var res = null; $.ajax({ type: "POST", url: "request1.php", data: $('#form_id').serialize(), cache: false, success: function(data1){ res= data1; } }); return res; } function other() { var res = null; $.ajax({ type: "POST", url: "request2.php", data: $('#form_id').serialize(), cache: false, success: function(data2){ res= data2; } }); return res; } $.when(mark(), other()).done(function(data1, data2) { console.log(data1); $(".results1").html(data1); console.log(data2); // Result $(".results2").html(data2); }); }); 
-one
source

Source: https://habr.com/ru/post/1495484/


All Articles