1

I would like to store a response result from an ajax call. This is because the ajax is the main API call used by several functions to extract information from an API.

I call callAPI function more than 8 times in my app. Of course, I can duplicate the function callAPI 8 times to properly get information but this is not cool way to code.

var result = callAPI("GET",url,'');
$('#status').val(result.success);
$('#output').val(result);
function callAPI(method_input, url_input, body_input){
    var urli = url_input;
    var datai = body_input;
    var method = method_input;

    $.ajax({
        url: urli,
        beforeSend: function(xhrObj){
            xhrObj.setRequestHeader("some header","some value");
        },
        type: method,
        data: datai,
    })
    .done(function(data,status) {
        console.log("success");
        console.log(data);
        return JSON.stringify(data);
    })
    .fail(function(data,status) {
        console.log("error");
        console.log(data);
        return JSON.stringify(data);
    });
  }

I tried to store the return value using var result = ajax(value); but the result is empty

is there any way to store return value of a function to a variable?

EDIT I Solved this problem by using callback function like below

function callbackResult(result){
$('#status').val(result.success);
$('#output').val(result);
}
function callAPI(method_input, url_input, body_input, callback){
    var urli = url_input;
    var datai = body_input;
    var method = method_input;

    $.ajax({
        url: urli,
        beforeSend: function(xhrObj){
            xhrObj.setRequestHeader("some header","some value");
        },
        type: method,
        data: datai,
    })
    .done(function(data,status) {
        console.log("success");
        console.log(data);
        return JSON.stringify(data);
        callback(data);
    })
    .fail(function(data,status) {
        console.log("error");
        console.log(data);
        return JSON.stringify(data);
        callback(data);
    });
  }

This was my first function to use a callback function and now I know what the callback function is.

Thank you guys all.

brian17nz
  • 11
  • 2
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Carcigenicate Apr 26 '19 at 12:09

2 Answers2

2

You need 'async': false, so:

var result = $.ajax({
    url: "https://api.github.com/users",
    'async': false,
    type: 'GET'
})
.done(function(data,status) {
    console.log("success");
})
.fail(function(data,status) {
    console.log("error");
});


console.log("result: " + result.responseText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  • Yes, current version is working like you mentioned but i need to call the callAPI 8 times and i need to put same code 8 times with little bit different result set which is in ".done(function(_){". So i would like to remove the code that replicated 8 times. To do that i need the result of the callAPI. this is my question. – brian17nz Apr 30 '19 at 20:28
  • Edited, you can check it now @brian17nz – Milenko Jevremovic Apr 30 '19 at 21:37
0

A few things to note:

  1. Instead of JSON.stringify() I think you want to use JSON.parse() to parse the JSON string that is probably been returned by your API.
  2. You can use the $.ajax option dataType to automatically parse the JSON string into an object.
  3. $.ajax() returns a promise which can be chained to add as many callbacks as needed.

A more elegant solution would be to return the promise from your function and chain your callbacks. Ex:

    function callAPI(method_input, url_input, body_input) {
      var urli = url_input;
      var datai = body_input;
      var method = method_input;

      return $.ajax({
          url: urli,
          // Automatically parses JSON response
          dataType: 'json', 
          beforeSend: function(xhrObj) {
            xhrObj.setRequestHeader("some header", "some value");
          },
          type: method,
          data: datai,
        })
        .done(function(data, status) {
          console.log("success");
          console.log(data);      
        })
        .fail(function(data, status) {
          console.log("error");
          console.log(data);      
        });
    }

    callAPI('GET', '').then(function(result){
      // Do something with my API result
    });

If you plan on making all request at once, with this solution you can consider aggregating all the request into a single promise with $.when(). Ex:

    $.when(
      callAPI('GET', ''),
      callAPI('GET', 'second'),
      callAPI('GET', 'third')
    ).then(function(firstResult, secondResult, thirdResult){
      // Do stuff with the result of all three requests
    });
Pablo
  • 5,897
  • 7
  • 34
  • 51