0

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);

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. so, to clarify i do not require console log i can do my actions there in place of that.. correct? I am appending css to the document with the contents of the array.
@StuartWickenden: Yes you are right, console.log is used here as an example to see result of each time but you can replace as per your needs.
2

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'
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.