Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
61
rated 0 times [  68] [ 7]  / answers: 1 / hits: 34387  / 14 Years ago, mon, october 18, 2010, 12:00:00

I would like to put an ajax call within a function since I use it repeatedly in multiple locations. I want a manipulated version of the response returned. Here's what I'm trying to do (greatly simplified).



a = getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: GET,
url: 'someURL',
success: function(response) {
return response;
});
}


What's happening, however, is that the append function is running before a has been defined in the getAjax function. Any thoughts?


More From » jquery

 Answers
22

There are two ways to taggle this. one is to use the success callback:



$.ajax({
type: GET,
url: 'someURL',
success: function(response) {
AppendResponse(response);
});


the other is to set async to false http://api.jquery.com/jQuery.ajax/:



var a;
getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: GET,
url: 'someURL',
async: false,
success: function(response) {
a = response;
});
}


Important note on non async:



Cross-domain requests and dataType: jsonp requests do not support synchronous operation.


[#95271] Friday, October 15, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janayr

Total Points: 80
Total Questions: 80
Total Answers: 114

Location: Venezuela
Member since Sat, Aug 22, 2020
4 Years ago
;