In this article I gave a brief intro to using JSON to pass JavaScript arrays to PHP via Ajax. I’ve done a bit more with json since then and with the help of a co-worker discovered how to get javascript objects working together with php utilizing json.
Passing Multiple JavaScript objects to PHP
JavaScript class:
1 2 3 4 5 6 | function product(id,name,price) { this.id=id; this.name=name; this.price=price; } |
Above we just create a simple javascript class that we will call below.
Putting JavaScript objects into JavaScript array:
1 2 | var object = new product('222','spectacular fizz','3.59') var productsArr[productsArr.length] = object; |
We can now add as many of the these objects as we would like to the products array. So lets say we have an array that looks like this below…
1 2 3 | productsArr[0] = object... productsArr[1] = object... productsArr[2] = object... |
…and we want to pass it over to PHP. So we use the following code to turn it into a JSON string.
1 | var productsJSON = JSON.stringify(productsArr); |
Now we need to do an AJAX Post and on the PHP side we decode the JSON string (note you only need to stripcslashes if magic quotes its turned on):
1 | $productsArr = $this->json->decode(stripcslashes($productsJSON)); |
Now we can reference these objects multiple ways. One if we are just continuously looping through we can use a foreach:
1 2 3 4 5 6 | foreach($productsArr as $product) { echo $product->id; echo $product->name; echo $product->price; } |
Or of course we can reference the object directly by its index in the array.
1 | echo $productsArr[1]->name; |
Pretty cool huh.