123
123

Reputation: 119

how to make the json data into jquery code?

the php json_encode($object) result is

[{"price_id":"1","website_id":"0","price_qty":2,"price":"90.0000"},
 {"price_id":"2","website_id":"0","price_qty":5,"price":"80.0000"},
 {"price_id":"3","website_id":"0","price_qty":8,"price":"70.0000"}]

someone tell me, var sorted = arrayWithJsonData.sort(function(a,b){}

how to use the above php json_encode($object) to arrayWithJsonData. i used the following way, but it shows TypeError: object.sort is not a function

first: in php i did: echo '<div style="display:none;" id="object">'.$object.'</div>'; then using in jquery

var object=jQuery("#object").text(); // first sort the array var sorted = object.sort(function(a,b){}

Upvotes: 0

Views: 74

Answers (3)

Odafe Ojenikoh
Odafe Ojenikoh

Reputation: 73

 var arrayWithJsonData = $.parseJSON($('#object').text());

$.parseJSON is a jQuery utitlity for converting a well-formed json string to a json object (jQuery doc: http://api.jquery.com/jQuery.parseJSON/). In our case, $('#object').text() method of the matched element returns the well-formed json string which is the output of the PHP function json_encode($object). Hope that helps.

Upvotes: 1

Diego
Diego

Reputation: 16714

var arrayWithJsonData = <?php json_encode($object) ?>;
var sorted = arrayWithJsonData.sort(function(a, b){
    // Sort criteria between a and b
});

Upvotes: 0

aleation
aleation

Reputation: 4844

You need to parse the object first so javascript(jQuery) can understand it:

JSON.parse(data);

Upvotes: 1

Related Questions