2

I'm sure the solution is staring me right in the eyes, but I just cannot see it. I am trying to load an object from an outside file source. I've tried it several which ways using jQuery's built in methods, but keep returning undefined. Is my issue the scope? I need partnerData right where it is because of other dependent methods in my script. I don't want to operate the rest of my site's functions from within the $.get callback. Any help is greatly appreciated, here's the code:

$(function() {

    var partnerData;

    $.get('data/partners.json', function(file) {
        partnerData = $.parseJSON(file);
    });

    console.log(partnerData); /* returns undefined instead of object */

});

EDIT:

Thanks for all the feedback everyone. This is the solution I went with:

var partnerData;

$.ajax({
    url: 'data/partners.json',
    dataType: 'json',
    async: false,
    success: function(data) {
        partnerData = data;
    }
});
0

4 Answers 4

5

The reason why you're seeing undefined is because ajax requests are asynchronous by default. This means your get method gets invoked and the code flow moves down to the next statement while the request executes in the background. Your callback function is later invoked when the request completes.

Using callback functions is a common pattern used in situations like this. But you seem to be saying you don't want to do or can't do that. In that case, you could use async: false which would force the request to be synchronous. Keep in mind however, that your code will be blocked on the request and if it's a long-lived request, the user experience will degrade as the browser will lock up.


P.S. You shouldn't need to parseJSON - if response has the correct mime-type set, jQuery will intelligently guess the type and parse the JSON automatically. And in case the server isn't sending back the correct mime-type, you can also explicitly tell jQuery what the expected return data type is; see the dataType argument to $.get() .


One way you might modify your code, to force synchronous requests:

$.ajax({
  type: 'GET',
  url: 'data/partners.json',
  success:  function(file){
               partnerData = $.parseJSON(file);
               //ideally you would perform a callback here 
               //and keep your requests asynchronous
            },
  dataType: 'json',
  async: false
});
Sign up to request clarification or add additional context in comments.

5 Comments

So, I'm logging my variable to the console before the request is complete?
Yes, exactly. Please see the edit to my answer - you can force the request to be synchronous but it's usually not a good idea and it should be the last resort.
What is my non-asynchronous alternative to retrieving file data in Javascript? Is there a built in method beside using the XMLHttpRequest object or $.ajax?
@65Fbef05: Don't make synchronous calls. Make your application work with callbacks, which is not difficult with JavaScript. All the code that has to work on the response should be inside or called from the response handler.
FWIW: $.get also accepts one more parameter, which is the data type: $.get('data/partners.json', function(file) {...}, 'json');.
1

function is proccessed to the end event when ajax is still being proccessed. insert it into callback function

$(function() {
    var partnerData;
    $.get('data/partners.json', function(file) {
        partnerData = $.parseJSON(file);
        console.log(partnerData);
    });
});

Comments

1

I would say that your problem is the same of the one that I just solved, if $.get is AJAX! and it is setting a variable, to read that variable outside the callback you need to wait the response! So you have to set async=false!

Comments

1

console.log in synchronous and get is async.

try:

$(function() {
    var partnerData;

    $.get('data/partners.json', function(file) {
        partnerData = $.parseJSON(file);
        test();
    });

    function test(){
        console.log(partnerData); 
    }
});

Comments

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.