Tom
Tom

Reputation: 9653

How to parse json data from php to jQuery

I have a curl statement that pulls json formatted array to php. I then want to transfer this array to jQuery so that the client side will hold the array. I'm currently using the below method:

<script>var obj = jQuery.parseJSON( <?php echo var_dump($json_short); ?> );</script>

The client sees something like:

<script>var obj = jQuery.parseJSON( array(1) {
  ["search"]=>
  array(50) {
    [0]=>
    array(6) {
      ["id"]=>
      string(6) "641279"
      ["description"]=>
      string(36) "Instyle - Responsive Portfolio Theme"
      ["url"]=>
      string(69) "http://themeforest.net/item/instyle-responsive-portfolio-theme/641279"
      ["type"]=>
      string(9) "wordpress"
      ["sales"]=>
      string(3) "135"
      ["rating"]=>
      string(3) "4.5"
    }
    ....
  }
}
 );</script>

Will obj now hold the array? is this the right way becuase I'm getting an error:

Uncaught SyntaxError: Unexpected token { 

Upvotes: 0

Views: 800

Answers (5)

Sam Pettersson
Sam Pettersson

Reputation: 3227

the var_dump function doesn't dump it as a json object.

use json_encode instead of var_dump.

Upvotes: 0

jona303
jona303

Reputation: 1568

I don't understand what you're trying with <script>var obj = jQuery.parseJSON( <?php echo var_dump($json_short); ?> );</script>

in PHP try echo json_encode($json_short);

Upvotes: 0

Pitchinnate
Pitchinnate

Reputation: 7566

Don't use var_dump first off. Next make sure you have converted your variable to a json array you have a normal array.

<script>var obj = jQuery.parseJSON( <?php echo json_encode($json_short); ?> );</script>

Upvotes: -1

Jage
Jage

Reputation: 8096

PHP has json_encode function already, you should use that.

Would look like:

<script>
var a = <?php echo json_encode($json_short); ?>;

</script>

Upvotes: 2

Emilio Rodriguez
Emilio Rodriguez

Reputation: 5749

You cannot use a direct dump, you need to json_encode first:

<script>var obj = <?php echo json_encode($json_short) ?>;</script>

Upvotes: 1

Related Questions