-1

I have a javascript function in my code which fetch data from a server using a ajax post request.

function fetchData(keyword)
{
    $.post(
        'http://example.com/apiv5/ajax/',
        {
            command: 'fetchxxx',
            token: 'xxxyyyzzz',
            data: keyword
        },
        function(data)
        {
            return data;
        }
    );
}

i need to concatenate the data into a variable like this, here i actually call the function.

var msg = '<p class="question">'+thisGuy.data('description')+'</p>'+fetchData(thisGuy.data('title'));

Note that here thisGuy = $(this);

Now the problem is , the fetchData() function take few seconds to fetch and load the data but in the meantime javascript skip this process and put a 'undefined' as if the returned value of this function.

Now how can i tell them to wait until it fetch the data and once it done then concatenate data in that variable? i have seen the wait() method but can not understand how to use it.

rakibtg
  • 5,521
  • 11
  • 50
  • 73

2 Answers2

1

You should understand that for any async call you cannot return anything from function. Only thing you can do it is wait for the request to complete and access the response in the callback.

Since the jQuery.post method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the .done() method. Take a look at documentation here https://api.jquery.com/deferred.done/

Try something like this.

function showMsg () {
    var thisGuy = $(this);

    fetchData(thisGuy.data('title'))
   .done(function (data) {
       var msg = '<p class="question">'+thisGuy.data('description')+'</p>'+data);
       //Now you can use the msg 
    });
}

function fetchData(keyword)
{
    return $.post('http://example.com/apiv5/ajax/',
        {
            command: 'fetchxxx',
            token: 'xxxyyyzzz',
            data: keyword
        });
}
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

Turn fetchData into a promise and resolve it in the callback of the Ajax query

Datsik
  • 14,453
  • 14
  • 80
  • 121