0

How can I get I return the response in ajax call,

I have tried with below code

function getDiscountAmount()
{
    for (var i = 0; i < invoice_ids.length; i++) {
        promises.push(getInvoiceAmountData(amount_tds, invoice_ids[i]));
    }
    Promise.all(promises).then((responses) => {
        var data= responses // need to return the response here
    })
    return data;
    function getInvoiceAmountData(amount_tds, invoice_id) {
        return $.ajax({
            url: "payments/getInvoiceAmount",
            method: "post",
            dataType: 'json',
            data: {"amount_tds": amount_tds, "invoice_id":invoice_id}
        });
    }
 }

And now get that response in different function

  function getResponse()
  {
      console.log(getDiscountAmount()) //it gives undefined
  }
jikos
  • 41
  • 5

3 Answers3

1

You are doing it right, just use the promises at correct place.

function getDiscountAmount()
{
    var promises = [];
    for (var i = 0; i < invoice_ids.length; i++) {
       promises.push(getInvoiceAmountData(amount_tds, invoice_ids[i]));
    }
    Promise.all(promises).then((responses) => {
        var data= responses // need to return the response here
    })
    return data;
}

Use a promise object in the ajax function

function getInvoiceAmountData(amount_tds, invoice_id) {
    return new Promise(function(resolve, reject){
          $.ajax({
            url: "payments/getInvoiceAmount",
            method: "post",
            dataType: 'json',
            data: {"amount_tds": amount_tds, "invoice_id":invoice_id},
            success: function(data){
                resolve(data);
            },
            error: function(error){
                reject(error);
            });
    });
}
mayank
  • 543
  • 4
  • 14
0
function getResponse()
  {
    console.log(getDiscountAmount().success(function(data){
         //data is your response
    });
  }

read more here: jQuery: Return data after ajax call success

sander
  • 719
  • 2
  • 9
  • 21
0

you should try easy ajax return function but you are doing that in complex way:

try this:

function test() {
     myFunction(function(d) {
     console.log(d);
 });
}

function myFunction(callback) {
  var data;
  $.ajax({
    url: 'url',
    data: 'data to send',
    success: function (resp) {
        data = resp;
        callback(data);
    },
    error: function () {}
  });
}
Therichpost
  • 1,759
  • 2
  • 14
  • 19