Returning the response from an Ajax call

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 65

Returning the response from an Ajax call

Hi,
I have a function sendAjax() which makes an Ajax request (with jQuery). How can I return the response from sendAjax()?
I tried to return the value from the success response, as well as assigning the response to a local variable inside the function and return that one, but none of those ways actually return the response.

Code: Select all

function sendAjax(url, datasend) {
  var result;

  $.ajax({
    url: url,
    data: datasend,
    success: function(response) {
      result = response;
      // return response;    // <- tried that one as well
    }
  });

    return result;
}

var result = sendAjax('file.php', 'id=9');    // always ends up being `undefined`

MarPlo
Hi,
I usually use a callback function that is passed as argument to the Ajax function.
The callback function is accessed when success, receives the response, and handles it.

Code: Select all

function sendAjax(url, datasend, callback) {
  $.ajax({
    url: url,
    data: datasend,
    success: function(response) {
      callback(response);
    }
  });
}

// the callback function
function ajaxRe(resp) {
  // do whatever you want with resp
}

sendAjax('file.php', 'id=9', ajaxRe);

Similar Topics