0

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

soum
  • 1,131
  • 3
  • 20
  • 47
  • Same question is asked ten times a day. Possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – user229044 Mar 29 '14 at 02:17

2 Answers2

1

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.

000
  • 26,951
  • 10
  • 71
  • 101
  • @joe-but I am actually doing this server side $json = json_encode($obj, JSON_PRETTY_PRINT); echo $json; thats the reason I am converting into an object. Should I not approach it like then? – soum Mar 29 '14 at 02:29
  • JQuery will automatically parse the json for you. You do not need to parse it yourself. – 000 Mar 29 '14 at 03:28
0

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.

Khanh TO
  • 48,509
  • 13
  • 99
  • 115