2

I'm trying to get some data into a variable to use in a template. I've used <?php file_get_contents(...) in a file called get.php as a proxy to avoid cross-origin issue.

The code below works, but gives a warning that 'async' : false is deprecated. However when I change it to true it returns null.

What am I missing please? What is the correct, modern approach to achieving what I'm trying to do?

$(document).ready(function(){

var json = (function () {
    var json = null;
    $.ajax({
        'async': false,
        'global': false,
        'url': 'get.php',
        'dataType': "json",
        'success': function (data) {
            json = data;
        }
    });
    return json;
})(); 

console.log(json);

});
weir
  • 4,521
  • 2
  • 29
  • 42
Robin Andrews
  • 3,514
  • 11
  • 43
  • 111
  • Try putting `console.log(json);` inside `success` and read about why use **async with ajax** – Guruprasad J Rao Mar 02 '17 at 19:27
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – apsillers Mar 02 '17 at 19:29

2 Answers2

2

Problem

jQuery's $.ajax() is an asynchronous call, and the result is that console.log() is running before you finished retrieving the data.

Solution

$.ajax returns a jqXHR object. We'll use the .done() method of this object to finish out the async call. Like so:

$(document).ready(function(){

    var def = $ajax({
        global: false,
        url: 'get.php',
        dataType: 'json'
    });

    // Pass in the completion callback here
    def.done(function(data) {
        console.log(data);
    });
});

The .done() method will be called when the AJAX call has completed and log out the JSON data.

Community
  • 1
  • 1
Joshua Kleveter
  • 1,769
  • 17
  • 23
1

That is because console.log(json); is running before your success callback. If you move to immediately after json = data; it would work with 'async' : true.

weir
  • 4,521
  • 2
  • 29
  • 42
  • The thing is I need the `json` variable to be available to use in an HTML page with the script included. This works with the synchronous version. How can I achieve this please? Can my code be tweaked to make this happen or is the approach flawed? – Robin Andrews Mar 02 '17 at 21:50
  • You ought to read up, starting with the linked duplicate question in the comment from @aspillers. But one approach would be, wherever the code is that depends on `json`, ensure that code is in a `function` with a parameter called `json` (e.g. `function foo (json) { // code using json }`) and then replace the `success` callback with `'success': foo`. – weir Mar 02 '17 at 22:00