Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problems executing a jquery ajax call within a function

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?

like image 766
dwelch Avatar asked Oct 18 '10 22:10

dwelch


2 Answers

AJAX is asynchronous. This means that the code in the success handler is delayed until the request is successful, while the rest of the code continues as normal. You need to put the relevant code in the AJAX success handler:

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

Note that I have also optimised your body selector by using the native Javascript document.body rather than using the standard tag selector.


Edit Callback version

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

You can now do the code inline using a callback function:

getAjax(function(response) {
    $(document.body).append('<div>'+response+'</div>');
});

or

getAjax(function(response) {
    alert(response);
});

or whatever.

The code inside the anonymous function call will be processed when the AJAX request is complete.

like image 169
lonesomeday Avatar answered Sep 28 '22 12:09

lonesomeday


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.

like image 44
Niko Avatar answered Sep 28 '22 12:09

Niko