1

I make a request to a server with JQuery and the $.when method.

  $.when(ajaxRequest(param)).done(function(response){
    console.log(responseData);
  });

my ajax function looks like this:

function ajaxRequest(param){
  var requestedData;
  return $.ajax({
    type: 'POST',
    url: myurl,
    data: {
        setParam:param
    },
    error: function(data){
      console.log(data);
      return(data);
    }
  });
}

Everything works fine if the server returns a 200 OK. But if there was something wrong the server answers with 500. How can I return the response body to the calling method?

The errorbody is printed with console.log on the ajaxRequest method but its not returned to the calling method?

rockZ
  • 815
  • 1
  • 12
  • 28

1 Answers1

2

Given js at Question $.when() is not necessary as $.ajax() returns a jQuery promise object. var requestedData; is not set to a value, would be undefined at .done(); use response available at .then() or .done() as returned data; .then() to handle both success and error responses

function ajaxRequest(param){
  return $.ajax({
    type: 'POST',
    url: myurl,
    data: {
      setParam:param
    }
  });
}

ajaxRequest(param)
.then(function(response){
  console.log(response);
  return response
}
// handle errors at second function of `.then()`
, function err(jqxhr, textStatus, errorThrown) {
  console.log(textStatus, errorThrown);
  return errorThrown;
});
guest271314
  • 1
  • 15
  • 104
  • 177