user3392740
user3392740

Reputation: 445

Extracting responseJSON object

I am fairly new to ajax and Javascript I have this code

duration_reco = $.ajax({
    url : newurl, 
    dataType : 'json'
}).done(function (obj) {});

console.log(duration_reco);

The output I get is http://grab.by/v0lc I am interested in the responseJSON(last object in the snapshot). I have tried duration_reco.responsejSON, but it doesnt work. How can I get the vlue.

Edit

Just providing more code, so that you can help better

for(var i=1;i<=10;i++) 
{   
    duration_reco = $.ajax({
        url : newurl, 
        dataType : 'json'
    }).done(function (obj) {
        console.log(obj.data.duration); 
        //console.log(duration_reco.responseJSON());
        data[i - 1] = {
            "duration" : obj.data.duration
         };
     });
}

I tried to do something like this, but it seems neither 'i' nor 'data' is accessible inside. What are my other options

Upvotes: 1

Views: 10464

Answers (3)

thescientist
thescientist

Reputation: 2948

Your Ajax request is being done asynchronously, while your code is being executed linearly. You need to log the output in the callback function.

var duration_reco = {};

$.ajax({
    url : newurl, 
    dataType : 'json'
}).done(function (obj) {
  duration_reco = obj;
  console.log(duration_reco);
});

Upvotes: 2

Ziggy
Ziggy

Reputation: 22365

In comments here and there throughout this question you have said things like "I want to make it synchronous" and "can I access it outside". You are encountering one of the very common problems a learner will encounter when working with asynchronous code. You are exasperated because you want to write code like this:

  1. set up the call
  2. make the call
  3. deal with the results

Asynchronous requests, you feel, are just getting in the way. Don't feel this way! Don't get frustrated: learn about the problem and then get even. Here is a link to a great resource that can help you tame asynchronous code.

Edit: using the sample code you provided, I've crafted a minimal example of how you would set this all up with promises. Check out the working fiddle.

// global variables: find a better way!
var data = [];
var count = 0;

// a function that returns a promise can be "waited for"
var many_requests = function () {
    var promise = $.Deferred();

    for(var i = 0; i < 10; i++) {   
        make_one_request(i, promise);
    }

    return promise; // "I promise one day I'll be an array of responses"
};

var make_one_request = function (index, promise) {

    $.ajax({
        url : '/echo/json/', 
        dataType : 'json',
        method: 'post', // <---- I'm making a POST because this is a fiddle
                        //       you will still use a GET
        data: {}, // <-- your data here
        success: function (response) {
            // these will run out of order, but your array will be ordered
            data[index] = response;
            console.log(index);

            // if the time has come, resolve the promise
            count++;
            if (count == 10) {
                promise.resolve(data); // OK! I'm an array of responses now!
            }
        }
    });
};

// I will wait until I have an array of response data
$.when(many_requests()).then( function (data) {

    // woo!
    console.log(data); 
});

In particular, pay attention to the console.log statement in the success function. The results are being returned out of order, but your array is still being indexed in the correct order. The callback to the then function will only run when the promise returned by many_requests is resolved.

Maybe this will work for you, maybe it won't, but the really important thing is: when you encounter a new kind of programming, a new pattern, or a new technique... don't try to run away and hide in your old paradigm! Embrace what is new and interesting, learn as much as you can, and then choose the techniques you love most and keep them in your tool belt.

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You have access in the .done function where obj is the parameter.

}).done(function (obj) {
    //console.log(obj); //your response
});

Upvotes: 0

Related Questions