Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I'm getting json response from my webserver by $.getJSON . This is the response :

[{"id":"1","latitude":"28.63","longitude":"77.21","price":"0"},{"id":"2","latitude":"28.71","longitude":"77.19","price":"100"}]

And this is my javascript code to convert this response to arrays :

var i = 0;
var vehicleId = $('#selectVehicle option:selected').val();
$.getJSON('getFillingDetails.php', {id : vehicleId}, function(data){
    var lat = [];
    var lon = [];
    var price = [];
    $.each(data, function(key, value){
        lat.push(value.latitude);
        lon.push(value.longitude);
        price.push(value.price);
        i++;
    });
});
console.log(i);

But when I see the value of i in console it doesn't changes . it's still 0. It means nothing is happening inside $.each() . I'm totally new to javascript. Any help will be appreciated.

share|improve this question
 
because it is a asynchronous request –  Arun P Johny Jul 17 at 5:52
 
Your code works just fine in a fiddle jsfiddle.net/tBUnz –  Benjamin Gruenbaum Jul 17 at 5:53
2  
@ArunPJohny his code is inside a callback of $.getJSON. –  Benjamin Gruenbaum Jul 17 at 5:54
 
@BenjaminGruenbaum no it is not .. I've edited the question with formatted code –  Arun P Johny Jul 17 at 5:55
 
@BenjaminGruenbaum the variable i is incremented inside the async callback –  Arun P Johny Jul 17 at 5:56
show 3 more comments

marked as duplicate by Arun P Johny, Benjamin Gruenbaum, Yogesh Suthar, Mr. Alien, Joe Jul 17 at 13:04

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4 Answers

up vote 1 down vote accepted

Try this out:

var i = 0;
var vehicleId = $('#selectVehicle option:selected').val();
$.getJSON('getFillingDetails.php', {id : vehicleId}, function(data){
    var lat = [];
    var lon = [];
    var price = [];
    $.each(data, function (i, item) {
        $.each(item, function(key, value){
            lat.push(value.latitude);
            lon.push(value.longitude);
            price.push(value.price);
            i++;
        });
    });
    console.log(i);
});

Your main problem was that because AJAX is A(synchronous)J(avascript)A(nd)X(ML), notice asynchronous, you console.log(i) was being fired before the request was finished. The other problem I noticed was that you were trying to only loop though an object. While your JSON starts with an array which also have to be looped though.

Just a suggestion. Native loops are pretty easy and function faster. I suggestion not using $.each:

var i = 0;
var vehicleId = $('#selectVehicle option:selected').val();
$.getJSON('getFillingDetails.php', {id : vehicleId}, function(data){
    var lat = [];
    var lon = [];
    var price = [];
    for (var i = 0, item = data[i]; i < data.length; i++) {
        for (var key in item) {
            var value = key[item];
            lat.push(value.latitude);
            lon.push(value.longitude);
            price.push(value.price);
            i++;
        };
    };
    console.log(i);
});

Now, I realize that jQuery was made to make your job easier. But I think it is just causing developers to become lazy. I think jQuery is amazing. But i've stopped using $.each once I realized that native loops are easy c:

share|improve this answer
 
What are you talking about? –  Shawn31313 Jul 17 at 5:54
 
Oh, my bad. But the -1 wasn't necessary. –  Shawn31313 Jul 17 at 5:55
 
A -1 does not indicate me not liking you or anything personal. All it does is indicate that I found something wrong with your answer and wanted you to correct it. In the original version it was similar to OP's code, now that you moved the log to inside the callback it makes sense. –  Benjamin Gruenbaum Jul 17 at 5:58

Try this code

var i = 0;
var vehicleId = $('#selectVehicle option:selected').val();
var jsonData;
$.getJSON('getFillingDetails.php', {id : vehicleId}, function(data){

    jsonData = data;
});
var lat = [];
    var lon = [];
    var price = [];
$.each(jsonData, function(key, value){
        lat.push(value.latitude);
        lon.push(value.longitude);
        price.push(value.price);
        i++;
    });
console.log(i);
share|improve this answer
 
He wanted to log the last value of i, not the value on every iteration. –  Benjamin Gruenbaum Jul 17 at 5:59
 
hey says "value of i in console it doesn't changes . it's still 0. It means nothing is happening inside $.each()" the above modification will show that the value of i changing –  iJay Jul 17 at 6:02
 
Read his code carefully. His console.log is outside the getJSON which means deferred execution will stop it from incrementing before the AJAX returns. –  Benjamin Gruenbaum Jul 17 at 6:02
 
updated my code –  iJay Jul 17 at 6:08

Using asynchronous functions in javascript can sometimes be confusing, here is why

EXAMPLE:

var result = 'pending';
$.ajax({
  url: 'something.php',
  success: function() {
    result = 'success';
  }
});

Now if we want to use result here we would not get a good result

console.log(result); // 'pending'

So instead I think you're better off calling 'function' on that one like this

var makeArray = function( data ) {
    var i = 0,
        vehicleId = $('#selectVehicle option:selected').val(),
        lat = [], lon = [], price = [];

    $.each(data, function(key, value){
        lat.push(value.latitude);
        lon.push(value.longitude);
        price.push(value.price);
        i++;
    });
    console.log(i);
}; 

$.getJSON('getFillingDetails.php', {id : vehicleId}, function(data){
    makeArray( data );
});
share|improve this answer

Just use the index:

var data = [{"id":"1","latitude":"28.63","longitude":"77.21","price":"0"},
            {"id":"2","latitude":"28.71","longitude":"77.19","price":"100"},
            {"id":"2","latitude":"28.71","longitude":"77.19","price":"100"}];
var i;
var lat = [];
var lon = [];
var price = [];

$.each(data, function(index, value){
    lat.push(value.latitude);
    lon.push(value.longitude);
    price.push(value.price);
    i = index;
});

console.log(i);

Check out this fiddle, I think it should be doing what you want

http://jsfiddle.net/vmy3b/3/

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.