I am trying to get array value from JSON string, and I do the work with json_decode PHP.
<?php
$jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php');
$jsonDecoded=json_decode($jsonContent,true);
foreach($jsonEncoded['BMS'] as $p){
echo '
ID: '.$p['id'].'
Tipe: '.$p['type'].'
';
echo "<br>";
?>
The PHP code works, and give the result of array from JSON string.
And this is my Javascript code
<script>
var bmsdata = <?php echo $jsonDecoded ?>;
alert(bmsdata["1"].id); // For check, i want to see the id of row 1
</script>
But nothing was shown up.
Am i doing right so far? Or i missing something to pass the value from PHP to Javascript? Any suggestion will be appreciated.
$jsonDecoded is the decoded json.
Please change
var bmsdata = <?php echo $jsonDecoded ?>;
to
var bmsdata = <?php echo json_encode($jsonDecoded); ?>;
or use the already exisiting variable $jsonContent:
var bmsdata = <?php echo $jsonContent; ?>;
This one should work, as I lookup JSON at http://megarkarsa.com/gpsjson.php ;)
<script>
var bmsdata = <?php echo json_encode($jsonDecoded); ?>;
alert(bmsdata.BMS["1"].id); // For check, i want to see the id of row 1
</script>
You just forgot 'BMS' key ;)
Looks like you're injecting a decoded, PHP-representation of the data into your javascript. You probably (if you want to continue doing it this way) want to echo the encoded version (jsonContent) instead.
Ultimately, you might want to rethink the approach. Fetching the data via ajax is often an easier way to work with it, since you don't need to worry about writing bare javascript via php, which has all sorts of escaping issues to get right.
Related
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I am developing a web application in php, and I've used javascript many times. Now I need to use a php variable in javascript.
For example, a variable generated from a SQL query return, or a session variable, which are needed in the javascript section.
What is the best way to use a php variable in javascript?
Maybe you could do something like:
<script>
var a = <?php echo $a; ?>; //for numbers
</script>
That's one basic way of accomplishing what you want.
EDIT: As JiteshNK also pointed out, you could also do:
<script>
var a = <?php echo json_encode($a); ?>; //safest solution
</script>
You can do something like this :
If a normal variable:
<script type= "text/javascript">
var a = <?php echo $var; ?>;
</script>
OR
If you have json :
<script type= "text/javascript">
var a = <?php echo $json_encode($var); ?>;
</script>
If its simple string variable then use.
<script>
var a = "<?php echo $var; ?>";
</script>
If php variable is array then
var resultArray = <?php echo json_encode($varArr); ?>
// Use resultArray values in javascript
$.each(resultArray, function(index, value) {
}
I don't fully understand what you are trying to do.
Basically, I don't thing what you would like to do is possible.
Reason: JavaScript is running in the browser. At the time when your JavaScript code is executed, the page has already been loaded. At that time, there is no such thing as PHP available anymore. Your browser only knows about HTML.
PHP is running on the server and is used to "construct" or "build" or "compile" your HTML page.
What you definitely can do is: You can use PHP to create your JS code dynamically (like you already do that with your HTML file) and there use PHP to populate a JS variable with the contents of a PHP variable.
Good day,
I got a new script (for me it is) that allows you to create a draggable tree view.
The order of the tree structure can be changed and also stored.
I managed to send and fetch the updated structure.
However I have not yet succeeded in unserializing the string.
Before I am going to write my own logic to decode the array I would like to know if PHP knows some functionality by default to solve this issue?
Example
The String that I have :
spans-divs[0][id]=null&spans-divs[1][id]=null&spans-divs[1][children][0][id]=null&spans-divs[1][children][0][children][0][id]=null&spans-divs[2][id]=null&spans-divs[3][id]=null
The code that generates this string :
serialized[0].hash
I hope anyone could tell me what I have done wrong. OR IF this even a usable structure.
Thanks in advance
Note
The results are bing written by PHP to a file called test.txt
When I try to get the results I try it like this:
<?php
$cont = file_get_contents('test.txt');
$Str = parse_str($cont);
echo '->'.$Str.'<-';
?>
This produces : ><
Hence an empty string.
The following is a working solution:
<?php
$cont = file_get_contents('test.txt');
parse_str($cont, $Str);
echo print_r($Str);
?>
(* the array that comes out of it is pretty useless actually *) but THANKS
This is all you need:
$arr = [];
$string = "spans-divs[0][id]=null&spans-divs[1][id]=null&spans-divs[1][children][0][id]=null&spans-divs[1][children][0][children][0][id]=null&spans-divs[2][id]=null&spans-divs[3][id]=null";
parse_str($string, $arr);
var_dump($arr);
Source: http://php.net/manual/en/function.parse-str.php
I want to update innerhtml of div with id NotifyDiv
I want to change it with following html code.
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
I am using following code to change it.
echo "<script>document.getElementById('NotifyDiv').innerHTML='$html'</script>";
But no changes occur.
However it I remove id = 'js-news' from the above ul tag it works.But I'll need the id.
If you check the source code of your browser you will see this:
<script>document.getElementById('NotifyDiv').innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'</script>
So we can see that in the JavaScript string you are using apotrophes, but the string is already encloded with apostrophes, so it attempts to end the string early: (before the letter j in js-news)
'<ul id='js-news'><li>HELLO WORLD!</li></ul>'
This can be solved by using escaped quotation marks for the JS string:
echo "<script>document.getElementById('NotifyDiv').innerHTML=\"$html\"</script>";
Basically, the code you have causes a syntax error in JS:
echo "...innerHTML='$html'</script>";
expands to:
// opening ' closing ' => js-news === syntax error!
// \/ \/
echo "...innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'</script>";
Resulting JS code:
document.getElementById('NotifyDiv').innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'
The syntax highlighting shows the problem
Note the single quotes around $html and the single quotes inside the $html string. The best way to echo PHP values in JS would be to use json_encode:
echo "...document.getElementById('NotifyDiv').innerHTML=", json_encode($html), "</script>";
The output should be something like:
<script>document.getElementById('NotifyDiv').innerHTML="<ul id='js-news'><li>HELLO WORLD!<\/li><\/ul>"</script>
Now, those slashes are escaped, and you probably don't want that. Thankfully, there's a second parameter you can pass to json_encode: cf the docs. Passing JSON_UNESCAPED_SLASHES is what you need to do here:
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
echo "<script>document.getElementById('NotifyDiv').innerHTML=".json_encode($html, JSON_UNESCAPED_SLASHES)."</script>";
The output:
<script>document.getElementById('NotifyDiv').innerHTML="<ul id='js-news'><li>HELLO WORLD!</li></ul>"</script>
DEMO
Perfect ans to your query is as under (just copy n paste and check it)
<?php
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
?>
<script type="text/javascript">
document.getElementById('NotifyDiv').innerHTML="<?php echo $html; ?>";
</script>";
You need to pass PHP variable with PHP syntax that is <?php ?>
Even if we can mix PHP, JavaScript and HTML together, we need to initialize proper languages before using their variables in case of JavaScript and PHP.
So, final code should be:
echo "<script>document.getElementById('NotifyDiv').innerHTML = '<?php echo $html;?>'</script>";
Otherwise, everything looks correct.
This is similar to PHP generated content inside Javascript breaking script, however I'm not able to understand where I'm wrong.
Here is the brief. I'm trying to output 10 strings from MySQL DB into a javascript array s, (s[1] to s[10]) (stored in one MySQL table under columns pt1 to pt1 - info so code is understandable to all). (Note $apos is just the apostrophe string - not a concern here).
<?php
echo "<script>\n";
echo "var s = [];\n";
for($i=1;$i<=10;$i++) {
echo "s[".$i."] = ".$apos.$r['pt'.$i].$apos.";\n";
}
echo "</script>";
?>
It produces the right code when I look at the source by 'View Source' in browser:
<script>
var s = [];
s[1] = 'a';
s[2] = 'b';
.
.
s[10] = 'j';
</script>
However, this doesn't work as a script (meaning if I check in Google developer tools, and I click on content inside the 'script' tag elements, it is told to be 'text', and not 'script' in the bar below).
However if I remove the PHP, and manually write the whole script the same way, it works just fine. I have tried removing the \n linebreaks in the PHP code, but still the same problem.
Something in PHP is breaking the script. Can you help?
My best guess is that one (or more) of your strings contains a character (such as the apostrophe) which breaks the PHP output. Still the best solution was already prosposed by Passery in your comments section:
echo '<script>';
echo 'var s = ' . json_encode($info);
echo '</script>';
I think you may have been misreading the developer tools. When I look closely at Chrome, it does indeed identify your script as text, possibly because the default type is text/javascript. Putting an explicit type declaration on the <script> tag made no change.
However, when I add echo "alert('s[1]='+s[1]);"; after the for loop, the alert displays, and I am able to see the values of the other s[i] with the debugger.
In other words, I think your generated JavaScript worked all along.
I know you've already fixed the problem another way. I post this answer only in case it may help others.
Here is what I used for testing:
<?php
$a = "-abcdefghij";
$apos="'";
echo "<script type=\"text/javascript\">";
echo "var s = [];";
for($i=1;$i<=10;$i++) {
echo "s[".$i."] = ".$apos.$a[$i].$apos.";\n";
}
echo "alert('s[1]='+s[1]);";
echo "</script>";
?>
I a webpage written in php/html that adds the contents of a text box to a session array each time a submit button is pressed. What I need to be able to do is take the unknown number of elements in the session array and have access to each of them in the javascript portion of my code.
Here is the php portion of my code so far:
<?php
session_start();
if(!isset($_SESSION['answers']))
$_SESSION['answers'] = array();
?>
<?php
if (!empty($_POST['submit'])) {
unset($_POST['submit']);
$_SESSION['locations'][] = $_POST;
}
if (!empty($_POST['display'])){
foreach ($_SESSION['locations'] as $array){
echo "<script type='text/javascript'>alert('{$array['lat']}')</script>";
}
}
?>
This will display each as an alert, but I need them as variables that can be accessed in javascript.
Thanks in advance
Just encode your data as JSON. It will be parsed as JavaScript array/object literal by the browser:
var locations = <?php echo json_encode($_SESSION['locations']) ?>;
Having a variable for each element of the array is not a good solution.