Reputation: 4165
I am having this issue I have been struggling with for sometime and now I need help: I have the following array
array(2) {
[0]=>
object(stdClass)#4 (4) {
["id"]=>
string(1) "1"
["idMake"]=>
string(1) "1"
["modelName"]=>
string(6) "Legend"
["modelYear"]=>
string(4) "1986"
}
[1]=>
object(stdClass)#5 (4) {
["id"]=>
string(1) "2"
["idMake"]=>
string(1) "1"
["modelName"]=>
string(3) "MDX"
["modelYear"]=>
string(4) "2000"
}
}
How can I use it the $.get()
function via jQuery in order to have something like this:
id Model Year
1 Legend 1986
2 MDX 2000
I have already tried the following:
a process.php file:
<?php
require 'DataLayer.class.php';
$dl = new DataLayer();
//get car make models
$models = $dl->getCarModels($id);
if(isset($models)){
echo json_encode(json_encode($models));
}
else{
echo 'failed';
}
?>
the getCarModels function:
public function getCarModels($id){
$stmt = $this->pdo->prepare("SELECT * FROM model WHERE idMake=? ORDER BY modelName");
$stmt->execute(array($id));
return $stmt->fetchAll(PDO::FETCH_OBJ);
}
Javascript function called upon clicking on some links
function getCarModels(id, make){
$.get(process.php, function(data){
var models = $.parseJSON(data);
for(var model in models.model.modelName){ // I got stuck here
}
});
}
Hope this makes any sense to someone. Thanks.
Just find out some similar issue at this link: php multidimensional array into jQuery I am giving a try.
Like I said from the start, my issue is quite similar to the one posted at this link php multidimensional array into jQuery. My only question is that I really don't know the reason why they use the json_encode() function twice as all I did to make it work properly is to remove one of the json_encode() functions.
Will appreciate some explanation of the reason why I used only jsan_encode() function to get the result I wanted while in most tutorial it has been two time before outputting the data.
Thanks again.
Upvotes: 1
Views: 815
Reputation: 171679
You don't need to use parseJSON within jQuery ajax, jQuery will already handle that. Your data is an array of objects. Here's example to loop over it with $.each
Your getCarModels()
function isn't set up to send data
function getCarModels(id, make){
var dataToServer={ id: id, make: make};/* need to match these keys to $_GET keys in php*/
$.get(process.php, dataToServer, function(data){
$.each( data, function(i, item){
$('body').append('<p>'+item.modelName+'</p>');
})
});
}
The php has issues also , it doesn't appear you are looking for $_GET from the ajax to pass to your query methods. I don't recognize the framework functions used in your php but to pass the ID to getCarModels in pphp you would need something like:
$id=$_GET['id'];
//get car make models
$models = $dl->getCarModels($id);
Upvotes: 1