Reputation: 2226
This is a silly question, but I'm trying to use the contents from var form_data
outside the ajax scope. How would I go about doing this? form_data only seems to exist inside the ajax function rather than outside even after declaring the variable outside of the ajax scope. I thought variables bubbled up until it finds where it was declared when var
isn't defined.
To clarify my question, how do I use the results from the server outside the success function? I don't want to limit myself to doing everything inside the ajax success callback.
$(function () {
var form_data;
$.ajax({
type: 'GET',
url: 'print_form.php',
data: {
//data sent to server
},
success: function (response) {
form_data = JSON.parse(response);
console.log(form_data); //object is printed out as expected
},
error: function () {
alert('AJAX failed for print_form');
}
});
console.log(form_data); //undefined
});
Upvotes: 0
Views: 48
Reputation: 4038
As AJAX stands for Asynchronous Javascript and Xml, so your code doesn't get blocked for an ajax operation being executed as it's asynchronous. In your case what happen is that when you are getting data through ajax your javascript doesn't stop continuing of execution and wait for the request to get success. Rather then that, while you are getting the data the rest of the code still gets executed. And that's why before you get the from the server through ajax request the form_data
already gets printed outside of the ajax request scope.
Let's test it :
Try initializing form_data
with any value. You'll find that now you won't get undefined outside the ajax where you printed the value. Rather you'll get the value you initialized the variable with.
Upvotes: 2
Reputation: 4946
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details. source: http://api.jquery.com/jquery.ajax/
Build your code as given in the docs:
I am having success with this setup that isolates the Ajax call.
function sendAjax(xhrdata) {
return $.ajax({
type: 'GET',
url: 'print_form.php',
data: xhrdata
}).promise();
}
sendAjax(data).done(function(response) {
form_data = JSON.parse(response);
console.log(form_data);
}
Upvotes: 0