0

Ok I've got this code in a file test.php:

<?php
$con = mysqli_connect("localhost", "user", "password", "DB");
if (mysqli_connect_errno()){
    echo "failed to connect:" . mysqli_connect_error();
}

$grab = mysqli_query($con, "SELECT * FROM DB");
$cars = array();
while($row = mysqli_fetch_assoc($grab)){
    array_push($cars, array("id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"];
}
echo json.encode($cars);

And I've got the jQuery code on my HTML page:

$.get("test.php", function($cars){
    $("itemNameLink1").html($cars.name);
    console.log($cars.name);
});

My next question is how do I access the data in my json_encoded array and use it in my jQuery on the HTML page. Right now I only get back undefined in console log. It was only my first try so wasn't disheartened by it. But any advise would be appreciated.

8
  • json.encode? that a typo?, any way, you need to loop the response, since this is most likely to have many rows Commented Sep 16, 2014 at 14:02
  • yeah sorry, I've done that twice now. Commented Sep 16, 2014 at 14:03
  • apparently cars is an array ? you are accessing name, which is probably a property of an individual car, not of the array. Commented Sep 16, 2014 at 14:04
  • well its an array of associative arrays. Commented Sep 16, 2014 at 14:06
  • @user3879560 What happens if you do console.log($cars);? Commented Sep 16, 2014 at 14:09

2 Answers 2

2

That's because you try to access name property of $cars array instead of name property of each car. You should to iterate through your array first:

for(var car in $cars){
    console.log(car.name);
} 

or

$cars.forEach(function(e){
    console.log(e);
});

if you maintain only modern browsers. Or use $.each method as @StartCoding mentioned.

AND, again as @StartCoding mentioned use $.getJSON instead of $.get or $.parseJSON($cars) if you've got a string in you response (it possible if your server returned wrong MIME-type [text/plain for example instead application/json]).

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

Comments

1
$.get("test.php", function($cars){
 $.each($.parseJSON($cars), function(i, val){
$("itemNameLink1").html(val.name);
console.log(val.name);
});
});

1 Comment

doesn't work, console log just gives a list of names. no change to itemNameLink1, it's ok, it'll take a bit to get my head round this.

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.