0

I start with jQuery, I want to retrieve and display the result of a custom ajax function that returns an array. But my console sends me back undefined:

undefined

The jQuery library CDN is correctly referenced in the < head > section. I read a lot of discussion about this site yet I can not fix the problem. However, I have the impression that my code is correct?

function query_suggest(query, lang){
    var result;

    $.ajax({
        url: 'http://suggestqueries.google.com/complete/search',
        data: {
            "hl": lang,
            "ds": "",
            "q": query,
            "client": "firefox"
        },
        jsonpCallback: 'msgsJsonCallback', 
        type: 'GET',
        headers: {
            "Accept-Language": lang,
            "Accept": "application/json",
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0"
        },
        dataType: 'jsonp',
        success: function(data) {       
            result = data;
            return result;

        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        },
        cache: true
    }); 
}

var suggest = query_suggest("chuck norris", "en");

console.log(suggest);
Sandra
  • 1,596
  • 15
  • 22
  • 1
    If you expect `query_suggest` to return response, it won't. Because http request is asynchronous process but the function returns immediately. You can only access response in `success` – Hikmat G. Jul 29 '18 at 18:57

1 Answers1

1

If you want to create a function wrapper around an ajax call, you can return a promise and do whatever you want with the response when the promise resolves:

function query_suggest(query, lang) {
    return new Promise(
        function (resolve, reject) {
            $.ajax({
                url: 'http://suggestqueries.google.com/complete/search',
                data: {
                    "hl": lang,
                    "ds": "",
                    "q": query,
                    "client": "firefox"
                },
                jsonpCallback: 'msgsJsonCallback',
                type: 'GET',
                headers: {
                    "Accept-Language": lang,
                    "Accept": "application/json",
                    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0"
                },
                dataType: 'jsonp',
                success: resolve,
                error: reject,
                cache: true
            });
        })
}

var suggest = query_suggest("chuck norris", "en");

suggest.then(result => {
    console.log(result) // on success
}).catch(function () {
    console.log(this, arguments) // on error
})
tao
  • 82,996
  • 16
  • 114
  • 150