jQuery ajax return value [duplicate]
How can I return the value "pinNumber" from jquery ajax so I can append it outside of the ajax. Here is my code
var x = pinLast + 1; for(i=x;i<=pinMany;i++) { var i = x++; var cardNumber = i.toPrecision(8).split('.').reverse().join(''); var pinNumber = ''; jQuery.ajax({ type: "POST", url: "data.php", data: "request_type=generator", async: false, success: function(msg){ var pinNumber = msg; return pinNumber; //pin number should return } }); jQuery('.pin_generated_table').append(cardNumber+' = '+pinNumber+'
'); // the variable pinNumber should be able to go here }
Please ask me if you don't understand.. ^^ thanks
Solution 1:
AJAX is asynchronous by default, you cannot return a value from the callback without making a synchronous call, which you almost certainly don't want to do.
You should supply a real callback function to the success:
handler, and put your program logic there.
Solution 2:
var pinNumber = $.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator",
async: false
}).responseText;
jQuery('.pin_generated_table').append(cardNumber+' = '+pinNumber+' ');
Solution 3:
It has to do with variable scope. The local variable pinNumber
you create is not accessible outside its wrapping function.
Perhaps declare pinNumber
globally or if it'll do the trick, simply stick your .append()
inside your success function.
Solution 4:
var _successEvent = function(response){
$('.pin_generated_table').append(cardNumber + ' = ' + response);
};
$.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator"
}).done(_successEvent);
Solution 5:
You can use this example:
window.variable = 'some data';
This make you variable global and you can access to this from anywhere