Structured data - javascript

Hello I am working on the data structure. I have following problems:
when I dump ($ data), I have all the info.
I am looking for how has integrated a php variable in json.
here is my piece of code. I have serious problem with concatenation. thank you in advance
<script type="application/ld+json">
{
"name":"<?php ($data[restaurant_name]);?>"
"author": {
"#type": "<?php.....?>",
"name": "<?php.....?>"
},
"datePublished": "<?php ($data[date]);?>",
"description": "<?php ($data[description]);?>",
}
</script>

Do not construct JSON objects like this, it's error-prone!
just using PHP construct an associative array, then use json_encode() function to create valid JSON object and pass whole to JS.
// variables
$name = 'Foo';
$type = 'bar';
$authorName = 'John';
// array
$data = [
'name' => $name,
'author' => [
'#type' => $type,
'name' => $authorName
]
];
// encode to JSON and display
echo json_encode($data);

Related

Unable to retrieve JSON value from PHP and Javascript

I have the following JSON below that I want to parse and get the value of the TotalRows. However, in my PHP and JavaScript it returns an error or undefined when I try to access it and I am not sure why.
For JavaScript:
var data = <?php echo json_encode($customers); ?>;
console.log(data.TotalRows)
I even placed console.log(data) and it gave me the JSON I posted and then I did console.log(data[0].TotalRows) and it give me undefined.
My code for PHP is, where $customers returns the JSON below:
$customers = $customerDB->findCustomer(5, 1);
$arr = json_decode($customers, true);
echo $arr["TotalRows"];
[
{
"TotalRows":91,
"Rows":[
{
"CompanyName":"Ana Trujillo Emparedados y helados",
"ContactName":"Ana Trujillo",
"ContactTitle":"Owner",
"City":"M\u00e9xico D.F.",
"Country":"Mexico"
},
{
"CompanyName":"Antonio Moreno Taquer\u00eda",
"ContactName":"Antonio Moreno",
"ContactTitle":"Owner",
"City":"M\u00e9xico D.F.",
"Country":"Mexico"
},
{
"CompanyName":"Around the Horn",
"ContactName":"Thomas Hardy",
"ContactTitle":"Sales Representative",
"City":"London",
"Country":"UK"
},
{
"CompanyName":"Berglunds snabbk\u00f6p",
"ContactName":"Christina Berglund",
"ContactTitle":"Order Administrator",
"City":"Lule\u00e5",
"Country":"Sweden"
},
{
"CompanyName":"Blauer See Delikatessen",
"ContactName":"Hanna Moos",
"ContactTitle":"Sales Representative",
"City":"Mannheim",
"Country":"Germany"
}
]
}
]
Its an array of object, so you would get TotalRows by
console.log(data[0].TotalRows);
Actually, I figured it out. The following worked:
var data = <?php echo json_encode($customers); ?>;
var data = JSON.parse(data);
console.log(data[0].TotalRows);

Symfony 4 - PHP convert multidimensional array to javascript

Hello I've this array in Symfony on my controller:
$array = [
"label" => [
"january",
"february"
],
"data" => [
0,
1
]
];
I wish I could convert it for use in Javascript.
The goal is that I can get in JS:
["january", "february"]
and
[0,1]
to use them as array variables
I tried json_encode($array), it works but I can't access to my array using {{array["label"}} in Twig in the Javascript block
Can someone help me please ?
EDIT : Okay guys, it works now, I did this :
Controller :
return $this->render('products/index.html.twig', [
"report" => json_encode($report),
]);
index.html.twig (javascript bloc)
const data = {{report | raw}};
Thanks all !
You do not have to call JSON.parse since the output of json_decode is a javascript literal. Just assign it to a variable.
var yourArray = <?php echo json_encode($array); ?>;
You can access property like this
alert(yourArray[0].Key);
You can try use:
PHP:
$array = [
"label" => [
"january",
"february"
],
"data" => [
0,
1
]
];
$response = new Response(json_encode($array));
$response->headers->set('Content-Type', 'application/json');
return $response;
JavaScript:
var data = JSON.parse(response);
console.log(data.label)
Hope help you.
What you get is a Json string, not an object, you first have to parse it in Javascript.
const data=JSON.parse(array);

Create JavaScript Object from PHP to hold user list with user data fields

I am building a Project management app using JavaScript and PHP.
Many of my JavaScript files will need access to a user list from my backend database. To increase performance or server hits I would like to build the user list with user data attached 1 time in PHP and print it to the screen as a JavaScript Object which my other JavaScript files can then access to get users data.
Assuming I have 20 users.
I need to have access to these user fields in ALL my JavaScript app/objects:
User name
User ID
User ACL role
User gravatar image URL
I am uncertain if I should generate a JavaScript Object with my PHP of the userlist or if it needs to be generated as JSON?
Also which ever it be, object or JSON, can you please show how it should be formatted to include multiple user records in the list and then how I would access a users data from my other JavaScript files assuming I have the user's ID.
So if I have user ID 1, I can call a function or object from my other JavaScript files and they will have access to all data for that user with ID 1 by getting it from the JavaScript that my PHP would print into the header of page.
Any help please?
Ideally I think something like being able to call:
var user = cureentJsObject.getUser(userId);
user.gravatarUrl // https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG
user.username // JasonDavis
user.role // admin
Being able to do something like that inside of my other JavaScript object/apps based on the data in the header of screen for userlist would be really nice but I am not certain how to do it?
UPDATE
I think this PHP would generate what I want. Just have to figure out the best way to access it in all of my objects in other JS files in the page
<?php
// PHP array
$userList = array(
array(
'id' => '1gdfgdfkn123423423',
'username' => 'JasonDavis',
'role' => 'admin',
'gravatar' => 'https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG'
),
array(
'id' => '2gdfgdfkn123423423',
'username' => 'John Doe',
'role' => 'user',
'gravatar' => 'https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG'
),
array(
'id' => '3gdfgdfkn123423423',
'username' => 'Rick James',
'role' => 'user',
'gravatar' => 'https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG'
),
);
?>
var users = <?php echo json_encode($userList) ?>;
JSON output:
var users = [{
"id": "1gdfgdfkn123423423",
"username": "JasonDavis",
"role": "admin",
"gravatar": "https:\/\/www.gravatar.com\/avatar\/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG"
}, {
"id": "2gdfgdfkn123423423",
"username": "John Doe",
"role": "user",
"gravatar": "https:\/\/www.gravatar.com\/avatar\/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG"
}, {
"id": "3gdfgdfkn123423423",
"username": "Rick James",
"role": "user",
"gravatar": "https:\/\/www.gravatar.com\/avatar\/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG"
}];
UPDATE 2
I can now access the user from the above...
<script>
function findById(source, id) {
for (var i = 0; i < source.length; i++) {
if (source[i].id === id) {
return source[i];
}
}
throw "Couldn't find object with id: " + id;
}
var users = <?php echo json_encode($userList) ?>;
var id = '2gdfgdfkn123423423';
var user = findById(users, id);
alert(user.gravatar);
</script>
I would say using JSON.
You can make a multidimensional array in PHP which encodes to JSON.
After you parse the JSON in JS you can access it like an object. E.g.:
myUserData[1].name
If you will always need all your users data, you can write an array of users in your PHP template as a JS array of objects. You don't need JSON. Something like:
<?php
$users_JS = array_map(function($user) {
return "{name: '{$user->name}', gravatar: '{$user->gravatar}'}";
}, $users)
?>
<head>
<title>PHP to JS</title>
<script>
window.MyApp.users = [
<?php echo implode(',', $users_JS); ?>
];
</script>
</head>
Now you can access your user list in window.MyApp.users.
If you need user data on demand (you don't know what data your app will need), you can do a little API in PHP that returns a user on JSON format:
<?php
$user = getUserFromId($_GET['id']);
header('Content-type: application/json');
echo json_encode($user);
And in JS:
$.ajax({
type: 'GET',
url: '/getUser.php', // URL of previuose PHP
data: {id: 3}
}).done(function(user3) {
// Do awesome things with user3
});
Obviously, this code needs validation, 404 if user id doesn't exists, etc, etc...
HTH!
You can use json_encode passing your user object to it.
The better way is to create a string with concatenating with '.' operator and in javascript use JSON.parse to make it a JSON object

How to extract parts of response of AJAX from PHP

Need some help here, i've been searching for related issues here but nothing seems to answer my problem. Ok so here how it goes
I have a simple search function that search through my database and I used an ajax to pass the data and get back the response and I manage to do that but my problem is that I can't seem to display the response the way I wanted to.
Here's my Ajax
$.ajax({
url: url, /// defined url
type: type, ///defined type
data: data, ///defined data
success: function(response){
//here I want to display something like
$('#display').html(the name of the employee);
}
});
Here's the ajax response
{
"employee": [{
"badgeno": "123 ",
"name": "John G. Doe",
"success": true
}]
}
{
"employee": [{
"badgeno": "456 ",
"name": "Jane G. Doe",
"success": true
}
I want to get the employee Name in there and display it in my page. How exactly am I gonna do that?
Thanks in advance. I'm still a newbie BTW
Here's the PHP
$getEmp = $this->Employee_model->search_emp($employee);
$count = count($getEmp);
if($getEmp){
for ($i=0; $i < $count; $i++) {
$data['employee'][$i] = array(
'badgeno' => $getEmp[$i]->BADGENO,
'name' => $getEmp[$i]->NAME,
'success' => true
);
echo json_encode($data);
}
print_r($data);
//$this->load->view('admin/home', $data);
}
Try:
employee_name= data.employee[0].name;
$('#display').html(employee_name);
Link to fiffle:
https://jsfiddle.net/fcz53htw/
If you have more then one name, first add them to array, only then print then json_encode of the array.
Now its wont wont work because you printing twice.
Try change your php to this:
$getEmp = $this->Employee_model->search_emp($employee);
$count = count($getEmp);
if($getEmp){
for ($i=0; $i < $count; $i++) {
$data['employee'][$i] = array(
'badgeno' => $getEmp[$i]->BADGENO,
'name' => $getEmp[$i]->NAME,
'success' => true
);
//echo json_encode($data);
}
echo json_encode($data);
//$this->load->view('admin/home', $data);
}
On php you are write the results twice delete the printr only use json_encode

Cant access data from json

I'm having trouble with JSON. I made this in PHP and I'm sending it to my JavaScript, but I can't get the values.
[
{
"book":[
{
"dir":"extract\/pg1065.epub"
},
{
"dir":"extract\/pg1065.epub\/1065\/0.css"
},
{
"dir":"extract\/pg1065.epub\/1065\/1.css"
},
}
{
"book":[
{
"dir":"extract\/pg6130-images.epub"
},
{
"dir":"extract\/pg6130-images.epub\/6130\/0.css"
},
}
]
I'm trying to access it with
var obj = JSON.parse(result);
alert(obj.book[0].dir[1]);
Anyone have any ideas?
First you need to validate your json, i have validate your json it gives error.
In your json dIr is id.
You have defined 3 dir id for same object this may be error.
EDIT: I missed it but first comment explains your missing your closing square brackets for the book arrays. Add that in and your good to go. Validate the JSON first.
You don't need to do JSON.parse you can simply do
var data = <?php echo "Your generated JSON code"; ?>;
Worth a note you can create your data structure in PHP and then simply use json_encode, then you can be sure it will be valid JSON
var data = <?php echo json_encode($yourData); ?>;
You have output an array so to get the first object you will do something like
var firstObj = data[0];
To get the first dir of the first book
var firstDir = data[0]["book"][0]["dir"];
[
{
"book": [
{
"dir": "extract/pg6130-images.epub"
},
{
"dir": "extract/pg6130-images.epub/6130/0.css"
}
]
},
{
"book2": [
{
"dir": "extract/pg6130-images.epub"
},
{
"dir": "extract/pg6130-images.epub/6130/0.css"
}
]
}
]
Your JSON was not valid i used: http://jsonlint.com/ to sort it!
Now you should be able to acess the data fine.
The code shown in the question is not a valid JSON. There are missing closing square brackets for each of the book arrays and (thanks to #punund) a missing comma between array members. The correct JSON would be this:
[
{
"book":[
{
"dir":"extract\/pg1065.epub"
},
{
"dir":"extract\/pg1065.epub\/1065\/0.css"
},
{
"dir":"extract\/pg1065.epub\/1065\/1.css"
}
]
},
{
"book":[
{
"dir":"extract\/pg6130-images.epub"
},
{
"dir":"extract\/pg6130-images.epub\/6130\/0.css"
}
]
}
]
You should not normally be printing JSON directly, but instead creating a JSON object in PHP and then using json_encode function. The following PHP will produce valid JSON for your scenario:
<?php
$result = array(
(object)array("book" => array((object)array("dir" => "extract/pg1065.epub"),
(object)array("dir" => "extract/pg1065.epub/1065/0.css"),
(object)array("dir" => "extract/pg1065.epub/1065/1.css"))),
(object)array("book" => array((object)array("dir" => "extract/pg6130-images.epub"),
(object)array("dir" => "extract/pg6130-images.epub/6130/0.css")))
);
echo json_encode($result);
?>

Categories