2

my first question. Normally just find out for myself but this is has got me beaten.

After an ajax send request, I used this php code to get all the rows and cols from my db:

$sql = "SELECT * FROM categories";
$result=$conn->query($sql);  
$arr = $result->fetch_all(MYSQLI_ASSOC);


print_r($arr)

gave me this output:

Array ( [0] => Array ( [cat_id] => 1 [cat_name] => Friends [checkbox] => checked ) [1] => Array ( [cat_id] => 2 [cat_name] => Favourites [checkbox] => checked ) [2] => Array ( [cat_id] => 3 [cat_name] => Drink [checkbox] => checked ) [3] => Array ( [cat_id] => 4 [cat_name] => Food [checkbox] => checked )
<br>

I encoded it using:

echo json_encode($result);

I then got the data into a js variable using:

result = Request.responseText;
var categories = JSON && JSON.parse(result) || $.parseJSON(result);

How do I access the rows of data stored in categories? I can only presume the JSON worked as categories is now a type [Object object] but I dont know how else to check.

2 Answers 2

1

categories should be an array. To test this, do

console.log(categories.length);

This should print the size of the array (number of rows). If this returns the expected result, use a simple for loop to iterate over the rows:

for (var i = 0, c = categories.length; i < c; ++i) {
    console.log(categories[i].cat_name);
}

Or, alternatively, use Array.forEach with a callback function:

categories.forEach(function(category) {
    console.log(category.cat_id + ' = ' + category.cat_name);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Sorted it as per below but thx for the tips and callback function, I will need that code later.
0

I woke up this morning and fixed this myself within 15mins, after having spent hours looking at this day before.

echo json_encode($result); //wrong variable

should be:

echo json.encode($arr); // correct variable 

Note to self: sleep on it!

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.