soum
soum

Reputation: 1159

not able to loop through an object

I am sending some values to server side using jquery post. And as a response I am getting back string. Then I am taking that and converting into an object by using JSON.parse()...when I am looking at the console log i am seeing the object, which looks fine to me. Now when I am trying to loop through the object and trying to retrieve values I am not able to iterate through it. I cant figure out what am I missing here. I am sending the value on an on change event..so basically the for loop would run every time on change event

Here is my js

$(function(){
    var categoryChoiceVal = '';
    var x = [];
    var html = '';
    $('select').change(function() {
        categoryChoiceVal = $('.categoryChoice option:selected').text().replace(/ /g, '%20');
        $.post("ajax.php", { categoryChoiceVal:categoryChoiceVal},function(data) {

            x = $.parseJSON(data)
            console.log(x);
        }); 
        $.each(x, function(){
            html += this.address;
        });
        $('.dataContainer').html(html);
    });

});

here is the page where I am doing this. http://soumghosh.com/otherProjects/phpDataOperation/eventcCalendar/testOne.php

Upvotes: 0

Views: 52

Answers (2)

000
000

Reputation: 27247

You do not need to parse a json response using $.post. Notice in the documentation (https://api.jquery.com/jQuery.post/) there is a fourth parameter dataType.

For example:

$.post( "test.php", { func: "getNameAndTime" }, function( data ) {
  console.log( data.name ); // John
  console.log( data.time ); // 2pm
}, "json");

No need to parse it.

The data is accessed only in the success callback, as in that example. Move your loop into your success callback.

Upvotes: 1

Khanh TO
Khanh TO

Reputation: 48982

Try putting your code in your callback:

$.post("ajax.php", { categoryChoiceVal:categoryChoiceVal},function(data) {
     x = $.parseJSON(data)
     console.log(x);

     $.each(x, function(){
          html += this.address;
     });
     $('.dataContainer').html(html);
}); 

$.post is asynch. When you call $.post, the response from server does not arrive yet. By putting inside the callback, you're assured that the response has arrived when your code is run.

Upvotes: 0

Related Questions