taking a php array and feeding it right into jscript

Oct 6, 03:16 PM

NOTE: mysql_real_escape_string needs to be replaced with addslashes – 2013-01-18
This procedure will take a php structure and pass it directly to a jscript array using the magic of JSON:

< script type=‘text/javascript’ src=‘http://www.json.org/json2.js’>
< / script >

< script type=‘text/javascript’ > const marksJavascriptArray = JSON.parse( ‘ < ? =addslashes ( json_encode($marksPhpArray)) ? > ‘ ) ;
< / script>

—same string using multiple variables for readability—

< ? php
$marksJson = json_encode($marksPhpArray);
$marksEscapeString = addslashes ($marksJson);
? >
< script type=‘text/javascript’ >

var marksJSTempVar = ‘ < ? = $marksEscapeString ?> ‘;
const marksJavascriptArray
= JSON.PARSE ( marksJSTempVar );
< / script>

1 – json_encode() – php call to take any array and turn it into JSON
2 – addslashes() [formerly mysql_real_escape_string] – php call to take a string and makes it ‘web friendly’
3 – JSON.parse() – jscript call to convert a JSON string and turn it into a jscript array (or the js equivalent)

so, we could have some rather hideous looking structure inside of $marksPhpArray, and with just one line of code, feed the entire structure right into js marksJavascriptArray!

and when using mysql, the php code practically disappears !

for perl:
use URI::Escape::JavaScript qw(escape unescape);
print escape(“this is Mark’s test”);

Mark Edwards

,

---

Commenting is closed for this article.

---