Page 1 of 1

Returning the response from an Ajax call

Posted: 24 Nov 2014, 14:13
by Marius
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`

Returning the response from an Ajax call

Posted: 24 Nov 2014, 14:43
by 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);