10

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?

5 Answers 5

16

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.

Sign up to request clarification or add additional context in comments.

3 Comments

just edit your code to replace 'a' in the success callback with 'response' since 'a' isn't defined
I could use that, but I don't always want to perform the same operations upon the successful ajax response. This is why I'd like to return the response.
Returning the response in this way is not what AJAX is designed for. I have updated the answer with a way to provide a way to set what you want to happen when you call the function.
8

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.

Comments

2

Why don't you return the response to another function in the success callback. This should handle your need for different responses:

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

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

Comments

2

One suggestion I have is to pass a trigger to the command you want to run into the AJAX function so that it will run after AJAX has received a response-

a = getAjax();
function getAjax() {
  $.ajax({
   type: "GET",
   url: 'someURL',
   success: function(response) {
     inputText(response);
  });
}

inputText(someText) {
$(document.body).append('<div>'+ someText +'</div>');
}

That way you can create if statements / other alternatives to continue to use the same AJAX command for different results

1 Comment

FWIW, you could shorten this to success: inputText. inputText is a reference to the function. Not only anonymous functions can be used as callbacks!
0

You can give a handler to the function getAjax(), but if the user needs the information for the next decision then why not wait using async: false?

function getAjax(handler) {
   $.ajax({
   type: "GET",
   url: 'someURL',
   success: function(response) {
     handler(response);
  });
};
function callGetAjax(response) {
  if(response === undefined) {
    getAjax(callGetAjax);
  } else {
    $('body').append('<div>'+response+'</div>');
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.