4 Replies - 552 Views - Last Post: 20 June 2013 - 01:52 PM

#1 Zel2008  Icon User is offline

  • D.I.C Addict

Reputation: 14
  • View blog
  • Posts: 790
  • Joined: 06-January 09

Encoding a PHP array for JSON

Posted 20 June 2013 - 11:49 AM

Hi all,

I have an array in PHP that I'm encoding in JSON, like this:

$var1 = "blah";
$var2 = "blah2";
$json_array = array();
$json_array['one'] = $var1;
$json_array['two'] = $var2;
// More things added to array dynamically here
echo json_encode( $json_array );



And reading in Javascript, like this:

    var data_object = array();
    // This has more things in it
    
    $.ajax({
        url:      'myFile.php',
        type:     'post',
        data:     data_object,
        dataType: 'json',
        cache:    false,
        success:  function( result ) {
            var parsed = jQuery.parseJSON( result );
            alert( parsed.one + " " + parsed.two );
        }
    });



When my alert pops up after AJAX, though, all I ever get is "[object Object]".

Does anyone know why my encoding is going wrong, and can help me figure out how to fix it?

Thanks,
Zel2008

This post has been edited by Zel2008: 20 June 2013 - 11:51 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Encoding a PHP array for JSON

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3561
  • View blog
  • Posts: 10,358
  • Joined: 08-June 10

Re: Encoding a PHP array for JSON

Posted 20 June 2013 - 11:54 AM

what you observe and what you show here doesn’t make sense. you get "[object Object]" when you try to alert (convert to string) an object (and that also applies to an associative array from PHP).

best is, you log that to the console, that shows you more than an alert. console.log(parsed);
Was This Post Helpful? 1
  • +
  • -

#3 Zel2008  Icon User is offline

  • D.I.C Addict

Reputation: 14
  • View blog
  • Posts: 790
  • Joined: 06-January 09

Re: Encoding a PHP array for JSON

Posted 20 June 2013 - 11:57 AM

Thanks Dormilich,

It looks like with console.log the JSON string is right, I guess that just means I can't check a JSON string with an alert. Thanks for the info! :)

Zel2008
Was This Post Helpful? 0
  • +
  • -

#4 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3561
  • View blog
  • Posts: 10,358
  • Joined: 08-June 10

Re: Encoding a PHP array for JSON

Posted 20 June 2013 - 12:07 PM

a JSON string you can check without problems, the parsed JSON object is different, though.
Was This Post Helpful? 0
  • +
  • -

#5 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6081
  • View blog
  • Posts: 23,557
  • Joined: 23-August 08

Re: Encoding a PHP array for JSON

Posted 20 June 2013 - 01:52 PM

You could use JSON.stringify() to display in an alert.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1