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);

});
2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.