Reputation: 863
I have a JSON
encoded array, to which i am returning to an AJAX
request.
I need to place the JSON
array into a JS Array so i can cycle through each array of data to perform an action.
Q. How do i place the JSON
array contents into a JS
array efficiently?
The PHP/JSON Returned to the AJAX
$sql = 'SELECT *
FROM btn_color_presets
';
$result = mysqli_query($sql);
$array = array(); //
while($row = mysql_fetch_assoc($result)) //
{
$array[] = $row;
$index++;
}
header("Content-type: application/json");
echo json_encode($array);
Upvotes: 0
Views: 496
Reputation: 3566
Adding to Safraz answer:
If you're using jQuery
, there's another way to do that. Simply add json
as last parameter to your ajax
calls. It tells jQuery
that some json
content will be returned, so success
function get already parsed json
.
Below example shows you simple way to achieve this. There's simple json
property accessing (result.message
), as well as each
loop that iterates through whole array/object. If you will return more structurized json, containing list of object, you can access it inside each
loop calling value.objectfield
.
Example:
//Assuming, that your `json` looks like this:
{
message: 'Hello!',
result: 1
}
$.post(
'example.com',
{data1: 1, data2: 2},
function(response){
console.log(response.message) //prints 'hello'
console.log(response.result) //prints '1'
//iterate throught every field in json:
$(response).each(function(index, value){
console.log("key: " + index + " value: " + value);
});
},
'json'
)
Upvotes: 2
Reputation: 382806
You can use JSON.parse
function to do so:
var myObject = JSON.parse(response_from_php);
// loop over each item
for (var i in myObject) {
if (myObject.hasOwnProperty(i)) {
console.log(myObject[i]);
}
}
You can also use jQuery.parseJSON()
if you are using jQuery, however jQuery also uses same function under the hood as priority if available.
Upvotes: 2