I have returned data from php (using json):
"[4, [{
"quantity": "1",
"name": "item 1",
"price": "2",
"currency": "GBP",
"description": "item 1 description"
}, {
"quantity": "1",
"name": "item 1",
"price": "2",
"currency": "GBP",
"description": "item 1 description"
}]]"
Then how do I access the data. It used to return use the second part:
[{
"quantity": "1",
"name": "item 1",
"price": "2",
"currency": "GBP",
"description": "item 1 description"
}, {
"quantity": "1",
"name": "item 1",
"price": "2",
"currency": "GBP",
"description": "item 1 description"
}]
which I used jQuery.parseJson to turn into an object but I can't seem to figure out how to add in the second part the number 4
help would be great
my php code is like this
$array['items'] = array();
$arrayOfMyNumbers = array();
$total = 0;
for( $i = 0; $i<2; $i++ ) {
$foo = new StdClass();
$foo->quantity = "1";
$foo->name = "item 1";
$foo->price = "2";
$foo->currency = "GBP";
$foo->description = "item 1 description";;
$arrayOfMyNumbers[] = $foo;
$total += ($foo->price*$foo->quantity);
}
$returnArray = array();
array_push($returnArray,$total,$arrayOfMyNumbers);
so I thought I'd be able to access that from javascript:
jsonArrayResponse = (jsonObj);
if(typeReq =="button"){
console.log("return is "+(jsonArrayResponse));
but it's how I get the 4 and then the second array part so I can convert it to an object.
Finally solve it!!!!
If you look at the original data you can see leading and trailing quotes. These were causing the json decode to fail. So I put in some regex and it work:
success: function (jsonObj) {
console.log(jsonObj);
jsonArrayResponse = (jsonObj);
var someStr = jsonObj.data.replace(/^"(.*)"$/, '$1');
console.log("some str is "+someStr);
parsed = JSON.parse(someStr);
console.log("this should be 4"+parsed[1]);
definitely one of these ones where it's very easy to miss. Thanks to Devlin who helped me track it down.