So, I started using Handlebars.js template to dispaly html code on success from a Jquery GET request. I then get an Array from my Controller (who gets it from my Model /database). In Handlebars I have to use the Array name to loop through it. I pass this Array using dataype JSON, and using json_encoding($array}
in my Controller.
The problem is my Array don't seem to get an array name, so I dont have an array name to refer to.
Code in Model:
public function getAllUserInfo() {
$this->selStmt->execute();
return $this->selStmt->fetchAll(PDO::FETCH_ASSOC);
}
Code in Controller:
private function getUserInfo() {
$userInfo = $GLOBALS["userModel"];
$userModel = $userInfo->getSearchResult();
$data = json_encode($userModel);
echo $data;
}
Code in View (Jquery):
$(function () {
$.ajax({
type: 'GET',
url: '?page=getUserInfo',
dataType: 'json',
success: function(data) {
createHTML(data);
$.each(data, function(i, item){
displayUsers(item);
});
}
});
});
displayUsers function is the handlebar function.
My problem is that the array I GET when loading page looks like this:
[{"userID":"19","name":"Testbruker2","username":"Test2","password":"test123","userLevel":"user","image":"tafjord.jpg","lastLogin":null,"email":"[email protected]"},{"userID":"20","name":"Testbruker3","username":"Test3","password":"test123","userLevel":"user","image":"tafjord.jpg","lastLogin":null,"email":"[email protected]"}]
And i want something like this:
{
Pets: [
{
"name": "Meowsy",
"species" : "cat",
"foods": {
"likes": ["tuna", "catnip"],
"dislikes": ["ham", "zucchini"]
}
},
{
"name": "Barky",
"species" : "dog",
"foods": {
"likes": ["bones", "carrots"],
"dislikes": ["tuna"]
}
},
{
"name": "Purrpaws",
"species" : "cat",
"foods": {
"likes": ["mice"],
"dislikes": ["cookies"]
}
}
]
}
In my handlebar container I have to write:
{{#each ARRAYNAME}}
//code here
{{/each}}
but i dont have a Array name to refer to..
Anyone knows how to accomplish this?
Thank you.
this will do the trick
$data = json_encode(array("DesiredArrayName" => $userModel));