i have a json object.
$json = json_decode($data,true);
it looks like-
array(5) {
["screenShareCode"]=>
string(9) "021113322"
["appletHtml"]=>
string(668) ""
["presenterParams"]=>
string(396) "aUsEN5gBYi4vlIEGpk0="
["viewerUrl"]=>
string(65) "http://api.leap.com/v2/viewer/021113322?accountid=mynet"
["origin"]=>
string(3) "API"
}
alert('?php echo $json; ?>');
when i am trying to assign this into javascript variable it gives me an error saying "unterminated string constant".
You don't decode it, in PHP or JavaScript. The contents of a JSON string is a valid JavaScript literal.
<?php
...
?>
<script ...>
var data=<?php echo $data; ?>;
alert(data["screenShareCode"]);
<?php
...
Try:
alert(<?php echo json_encode($json); ?>);
or:
alert(<?php echo $data; ?>);
You're a bit confused about terminology. $data is a JSON string, $json is a PHP array that you got by decoding the JSON string.
Try the following code. I have created a php file named sample.php. We have a php array named $data. Encode that data in to json using json_endode(). That results json formatted data. Then we can assign it into a java script variable like var jsonData = <?php echo $jsonData ?>; Note that this is done inside <script> tag.
<?php
// We have some data
$data = array(
"screenShareCode"=>"021113322",
"appletHtml"=>"",
"presenterParams"=>"aUsEN5gBYi4vlIEGpk0",
"viewerUrl"=>"http://api.screenleap.com/v2/viewer/021113322?accountid=mynet",
"origin"=>"API"
);
// Convert it into json format.
$jsonData = json_encode($data,true);
?>
<script>
// Assign that json data to a java-script variable
var jsonData = <?php echo $jsonData ?>;
// To view the full data
console.log(jsonData);
// You can take a specific data like this.
alert(jsonData.presenterParams);
</script>
Related
In my db I save the json in a custom field called usp-custom-12 like this:
[{"Mamma":["Papa"]}]
Then I try to decode that
<?php
$jsonTable = usp_get_meta(false, 'usp-custom-12');
?>
var data = <?php echo htmlspecialchars_decode($jsonTable); ?>;
But it is giving me
var data = "[{"Mamma":["Papa"]}]";
And a console log error:
Uncaught SyntaxError: Unexpected identifier
The full code:
<?php
$jsonTable = usp_get_meta(false, 'usp-custom-12');
?>
var data = "<?php echo htmlspecialchars_decode($jsonTable); ?>";
console.log(data);
data = JSON.parse (data);
data.forEach(obj => {
Object.keys(obj).forEach(key => {
$('#newTable thead tr').append($('<th>').text(key));
obj[key].forEach((e, i) => {
if(!$("#newTable tbody tr:eq("+i+")").length) $("<tr>").appendTo($("#newTable tbody"));
$("#newTable tbody tr:eq(" + i + ")").append($('<td>').text(e))
})
})
});
In this jsFiddle if you click save table you will see it generates a table identical to the top one, that's also logging in console the correct json: https://jsfiddle.net/fbh0o67o/74/
$jsonTable contains a JSON string with html entities encoded, since it's already JSON, you just have to decode the html etities and echo it as is. No JSON decoding is required, no quoting is required. Just HTML decode and echo it into your javascript.
var data = <?php echo htmlspecialchars_decode(usp_get_meta(false, 'usp-custom-12')); ?>;
data.forEach(obj => {
// Loop stuff here...
});
The issue is with the quotes inside the string "mama" you need to escape those quotes using addslashes method.
Try using the following:
var data = "<?php echo addslashes(htmlspecialchars_decode($jsonTable)); ?>";
JSON to PHP:
json_decode($string);
If you use the optional parameter $assoc as true - json_decode($string, true) will return associative array on success.
PHP to JSON:
json_encode($array);
PHP manuals:
json_encode()
json_decode()
So current setup is as following:
PHP:data.php
<?php
$method = $_SERVER['REQUEST_METHOD'];
$data = array(
"16508",
"16498",
"16506"
);
if ($method === "GET") {
echo json_encode($data);
}
?>
JS:
$.get("./page_asset/data.php").then(function(returned) {
data = JSON.parse(returned);
};
Now, how do I parse the data without getting the specific php page (as I don't want to rely on the specific php address such as "/page-asset/data.php").
For example:
PHP:
<?php
$data = array(
"16508",
"16498",
"16506"
);
?>
I simply want to pass these values to js without relying on the page url.
You can use PHP to create the Javascript in the original page. json_encode() can be used to convert a PHP value to the analogous JS literal.
<?php
$data = array(
"16508",
"16498",
"16506"
);
?>
<script>
var data = <?php echo json_encode($data); ?>;
</script>
You can use a hidden field:
<input id="my-data" type="hidden" value='<?php echo json_encode($data)?>' />
And then you can parse the input value from javascript:
var data = $.parseJSON($('#my-data').val());
Can you please let me know how I can pass Two Values from PHP file into a jQuery Ajax script. What I have is a Ajax call as:
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
alert(data);
})
});
</script>
and my PHP (captcha.php) is like:
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1;
?>
as you can see currently I am able to pass the value of the $number1 but I need to have both values($number1 and $number2). Can you please let me know how to achieve this?
Thanks
Instead of sending (invalid) HTML to the client, use a structured data format, such as JSON.
<?php
header("Content-Type: application/json");
$data = Array($number1, $number2);
print json_encode($data);
exit;
In the JavaScript, jQuery will now populate data with an array.
Why don't you make an array containing variables to return and json_encode it to parse it in JS?
echo json_encode(array($number1, $number2));
Make an array out of your values:
$array = array($number1, $number2);
Then parse it to json
$json = json_encode($array);
Then echo out the $json and you have multiple variables in your js!
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
data = data.split(",");
//Number 1
alert(data[0]);
//Number 2
alert(data[1]);
})
});
</script>
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1 .",". $number2;
?>
All this does is tells the php script to echo Number1,Number2 and then the javascript splits this string into an array from the ,
First Way
You can concatenate the two values seperating them by a special character like '_' like this
PHP
echo $number1 . '_' . $number2;
And then do like this in javascript
data = data.split('_'); // get an array with the two values
Second way
You can encode as JSON in php and do a json ajax request
PHP
$result = array($number1, $number2);
echo json_encode($result);
Javascript
$.getJSON('captcha.php',function(data){
console.log(data); //
});
I have a php file where I am outputing json.
<?php
header('Content-Type: application/json');
?>
var data = {
"cars": [
<?php foreach ($runshowcars as $rowscar):;?>
{
"id":"<?php echo $rowscar['id'] ?>",
"name":"<?php echo $rowscar['name'] ?>"
}
],
"boats": [
<?php foreach ($runshowboats as $rowsboat):;?>
{
"id":"<?php echo $rowsboat['id'] ?>",
"name":"<?php echo $rowsboat['name'] ?>"
}
],
};
This works however the output looks like this.
var data = {
"cars": [
{
"id":"1",
"name":"Ford"
}
,{
"id":"2",
"name":"Honda"
}
]
};
I want it to look like this.
var data = {"cars": [{"id":"1","name":"Ford"},{"id":"2","name":"Honda"}]};
The only way I have found to do this is to remove the white spaces from my php file, this is obviously not an ideal solution as it makes it very hard to maintain.
How can strip out all the white spaces here?
I have seen plenty of questions like this one, How to minify php page html output? however I can't get something like this working here as my data isn't in a variable?
Why don't you collect your data into an array and encode it to json.
Like this:
$data=array('cars'=>$runshowcars, 'boats'=>$runshowboats);
print json_encode($data);
(Otherwise you return javascript, and not json. At least if you prepend the result with the var data = part.)
Just create a multi dimensional associative array and use json_encode
You can remove everything outside <?php ?> like this :
<?php
header('...') ;
echo 'var data = {' ;
echo '"cars": [' ;
foreach ($runshowcars as $rowscar)
{
echo '{' ;
echo '"id":"'.$rowscar['id']?'",' ;
echo '"name":"'.$rowscar['name'] ;
echo '}' ;
}
echo '],' ;
...
?>
Or you can try json_encode php function (wich could be a better way imo) :
<?php
$data = Array('cars'=>$runshowcars,'boats'=>$runshowboats) ;
echo 'var data = '.json_encode($data) ;
?>
I have a curl statement that pulls json formatted array to php. I then want to transfer this array to jQuery so that the client side will hold the array. I'm currently using the below method:
<script>var obj = jQuery.parseJSON( <?php echo var_dump($json_short); ?> );</script>
The client sees something like:
<script>var obj = jQuery.parseJSON( array(1) {
["search"]=>
array(50) {
[0]=>
array(6) {
["id"]=>
string(6) "641279"
["description"]=>
string(36) "Instyle - Responsive Portfolio Theme"
["url"]=>
string(69) "http://themeforest.net/item/instyle-responsive-portfolio-theme/641279"
["type"]=>
string(9) "wordpress"
["sales"]=>
string(3) "135"
["rating"]=>
string(3) "4.5"
}
....
}
}
);</script>
Will obj now hold the array? is this the right way becuase I'm getting an error:
Uncaught SyntaxError: Unexpected token {
PHP has json_encode function already, you should use that.
Would look like:
<script>
var a = <?php echo json_encode($json_short); ?>;
</script>
You cannot use a direct dump, you need to json_encode first:
<script>var obj = <?php echo json_encode($json_short) ?>;</script>
I don't understand what you're trying with <script>var obj = jQuery.parseJSON( <?php echo var_dump($json_short); ?> );</script>
in PHP try echo json_encode($json_short);
the var_dump function doesn't dump it as a json object.
use json_encode instead of var_dump.
Don't use var_dump first off. Next make sure you have converted your variable to a json array you have a normal array.
<script>var obj = jQuery.parseJSON( <?php echo json_encode($json_short); ?> );</script>