0

I'm trying to return a string back after my Ajax is executed, however; I'm getting the word undefined instead of the string. I understand that the code is being executed asynchronously, but I don't understand how I can make a solution for my problem.

JS

function aggregator(field){
    var query = '{"aggs": { "group_by_date": { "terms": { "field": "' + field + '" } } } }';

     $.ajax({
        url: 'index.php',
        type: 'post',
        data: {
            qSet: query
        },
        success: function(message){
            return message;
        }
    });

}

   var results = aggregator("transactionDate");
   document.getElementById("results").innerHTML = results;

How do I make it so that my element in HTML has the returned value?

user2896120
  • 3,180
  • 4
  • 40
  • 100
  • 1
    Possible duplicate of [jQuery: Return data after ajax call success](https://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success) – mx0 Jun 05 '17 at 20:14
  • 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) – Jasen Jun 05 '17 at 20:15

1 Answers1

2

welcome to asynchronous programming. You must either process your return value inside the callback of the ajax function, or use some kind of deferred queue based on promises for example.

For a quick solution of your problem, try the first technique:

function aggregator(field,element){
    var query = '{"aggs": { "group_by_date": { "terms": { "field": "' + field + '" } } } }';

     $.ajax({
        url: 'index.php',
        type: 'post',
        data: {
            qSet: query
        },
        success: function(message){
            document.getElementById(element).innerHTML=message;
        }
    });

}

aggregator("transactionDate","results");
PA.
  • 28,486
  • 9
  • 71
  • 95