I am trying to copy a string in a php array to localStorage and the string is a date in this format: 2016-06-15
But the string becomes calculated before stored.
How do I preserv it as a string?
Example:
<?php
$test = array('2015-10-05','20151005');
echo $test[0]."<br>";
echo $test[1];
echo '<script>localStorage["test1a"] = '.$test[0].';</script>';
echo '<script>localStorage["test2a"] = '.$test[1].';</script>';
?>
<script>localStorage["test1b"] = "2015-10-05";</script>
<script>localStorage["test2b"] = "20151005";</script>
This will output:
2015-10-05
20151005
And in localStorage:
test1a 2000
test1b 2015-10-05
test2a 20151005
test2b 20151005
<?php
$test = array('2015-10-05','20151005');
echo $test[0]."<br>";
echo $test[1];
echo '<script>localStorage["test1a"] = "'.$test[0].'";</script>';
echo '<script>localStorage["test2a"] = "'.$test[1].'";</script>';
?>
<script>localStorage["test1b"] = "2015-10-05";</script>
<script>localStorage["test2b"] = "20151005";</script>
Note the Additional Quotes added '"' wrapping the array variable.
To explain why it does not store the value but calculate it is because you are throwing a string at browser and it interpretes as HTML or Javascript in this case.
Related
When I load a php page, i put within a javascript function, a name. The problem comes when this string has special chars like '.
Here I paste the code of a click event:
showSocialShare(event, '<?php echo $object->slug; ?>', '<?php echo htmlspecialchars($object->title); ?>', '<?php echo $object->image; ?>')
I thought that the function htmlspecialchars code somehow the string but the result is:
showSocialShare(event, '4049269', 'collection-'Noun'', '/img/Original.jpg')
As can be seen, at the second parameter, the name contains characters like ' and arises an error.
How can I avoid this?
Never output text from PHP directly into a Javascript context. As you're finding out, it's VERY easy to generate JS syntax errors.
Always use json_encode: e.g. given this
<?php $foo = 'bar'; ?>
<script>
var badly_broken = <?php echo $foo ?>;
var working_fine = <?php echo json_encode($foo); ?>;
</script>
You'll end up with
<script>
var badly_broken = bar; // oops - undefined variable "bar"
var working_fine = "bar";
</script>
And note that if you're outputting JS into an HTML attribute, you not only have to generate valid Javascript, you have to output valid HTML AS WELL:
<?php $foo = array('bar' => 'baz'); ?>
<a onclick="brokenCall(<?echo json_encode($foo) ?>)">
<a onclick="workinCall(<? echo htmlspecialchars(json_encode($foo)) ?>)">
produces:
<a onclick="brokenCall({"bar":"baz"})">
^--start attribute
^--end attribute - ruhroh
<a onclick="workingCall({"bar":"baz"}")>
I understand that the format for passing a PHP array to Javascript is:
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
I have a php function that stores some values in a longitude and latitude array. These array do hold the right values within php since print_r() within php shows me that the array is correct.
print_r($latitude_array);
print_r($longitude_array);
Now, I pass on this array to JS in this manner:
<script>
var lati_array = "<?php echo json_encode($latitude_array); ?>";
var longi_array = "<?php echo json_encode($longitude_array); ?>";
alert(lati_array[0]);
</script>
In the beginning, when I open the HTML file, it shows me an empty array (which is expected because the PHP arrays aren't filled yet). Then user enters something, the php arrays are filled up with longitudes and latitudes. These values should now be passed to JS. However, it doesn't alert anything after that. I can't be sure if array is successfully passed to JS. What am I missing?
Try this:
<script>
var data = <?php echo json_encode( $data ); ?>;
</script>
Try like below:
<?php
$array_var = array(111, 222, 333, 444);
?>
<script>
var array_var = "<?php echo json_encode($array_var); ?>";
console.log(array_var);
array_var = JSON.parse(array_var);
console.log(array_var);
alert(array_var[0]);
</script>
You are getting a string in lati_array , Try to convert it into json like this:
<script>
var lati_array = "<?php echo !empty($latitude_array) ? json_encode($latitude_array) : ''; ?>";
var longi_array = "<?php echo !empty($longitude_array) ? json_encode($longitude_array) : ''; ?>";
lati_array = JSON.parse(lati_array);
alert(lati_array[0]);
</script>
I have some javascript embedded into an html file that I am running in a browswer.
document.getElementById('home-search-text-inp').value = <?php echo htmlspecialchars($_GET['search_for']); ?>;
Why does this not fill the textbox?
Note that:
document.getElementById('home-search-text-inp').value = "hi";
puts "hi" into the textbox and:
<?php echo htmlspecialchars($_GET['search_for']); ?>
writes text just fine.
Thanks in advance
You're missing quotes around your string value:
document.getElementById('home-search-text-inp').value = <?php echo htmlspecialchars($_GET['search_for']); ?>;
^^^^ ^^^^
HERE HERE
should be:
document.getElementById('home-search-text-inp').value = "<?php echo htmlspecialchars($_GET['search_for']); ?>";
I've this problem at the var address line, i think to have write all correctly or not?
<?php for ($i = 1; $i <= count($data); $i++) { ?>
var address = "<?php echo $address[$i].','.$city[$i].','.$region[$i] ?>";
alert(address);
<?php } ?>
You're generating javascript with php and the error you get comes from the javascript part, not php. I guess that one of your variables like $address contains something that isn't valid in js strings, like a newline. The best practice is to use json_encode to encode values for use in javascript:
var address = <?php echo json_encode($address[$i].','.$city[$i].','.$region[$i]) ?>;
Here I am getting values from textarea in array variable.
After that I convert javascript variable to PHP variable and perform some processing over it.
After process completed again I convert PHP to JS and alert. But when I alert, it gives empty result.
<script>
$( "#convert" ).click(function() {
var arabic = document.getElementById("ar").value; // ar is id of text area
<?php $ar_terms = "<script>document.write(arabic)</script>"?>
<?php
$string=implode(",",$ar_terms);
$result = array();
foreach ($ar_terms as $term) {
// echo $Arabic->ar2en($term);
array_push($result, $Arabic->ar2en($term));
}
$result=implode(",",$result);
?>
var arabic = new Array();
arabic='<?php echo $result; ?>';
alert(arabic);
});
</script>
Entire code is here : https://gist.github.com/karimkhanp/d4ac41fa864fd8ae0521
You can do one thing in this scenario to pass the variable from PHP to js. You can convert the array using json_encode() before echoing:
$result=json_encode( implode(",",$result) );
As a result, when you assign this variable to js in the <?= ?> block, it will read the json string and thus the array will be assigned:
arabic='<?php echo $result; ?>';