Why does body onload require htmlentities on nested json_encode'd array? - javascript

I read database records, and create one PHP array() for each database record, then store each of these arrays as an element of a top-level PHP array(). The top level array is thus an array of arrays, and the nested arrays each contain the fields of one database record. Nothing special here.
I need to pass the nested array of database record arrays to two different javascript functions and so I use json_encode in PHP before passing the nested array:
CASE #1: the first pass of the nested json_encoded-d is to a Javascript function doSomeStuff( theNestedJsonEncodedArray) -- I used a hidden iframe technique to pass the nested array into javascript code (see below)
CASE #2: the other pass of the nested array is to my web page's body onload=handleLoad( theNestedJsonEncodedArray )
With Case #1, I do not need to use htmlentities( theNestedJsonEncodedArray ) in order for this json encoded array to be successfully used in my doSomeStuff() function.
With Case #2, the body onload=handleLoad( ) function will NOT EVEN EXECUTE. Unless I add an extra step. The extra step is this: after json_encode'ing the nested array, I have to call htmlentities() -- then and only then will my body onload=handleLoad( ) behave correctly.
I 100% fail to understand this. I do not understand why, in the case of my "PHP/iframe/javascript" scenario, json_encode() is sufficient to pass the nested array -- but my "body onload=handleLoad()** case, I need to use htmlentities() on the nested array, or the onload javascript function will not even execute.
Note here: there is zero html in my database records.
CASE #1 CODE -- uses a hidden iframe to pass javascript code to my web page:
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
$theTopLevelArray= array();
for($i = 0; $i < $numrows; $i++)
{
$theRow = mysql_fetch_row($result);
$recordNum = $theRow[0];
$lat = $theRow[1];
$lng = $theRow[2];
$city = $theRow[3];
$state = $theRow[4];
// EACH NESTED ARRAY IS A TOWN with City, State, Latitude, Longitude
$nestedArray = array( $lat, $lng, $i, $recordNum, $city, $state);
$theTopLevelArray[] = $nestedArray;
}
$jsonArray = json_encode($theTopLevelArray);
echo '<script type="text/javascript">' . "\n";
echo 'var parDoc = parent.document;' . "\n";
$sendToWebpageStr = "parent.doSomeStuff( $jsonArray );";
echo $sendToWebpageStr;
echo "\n".'</script>';
// And in my web page's javascript code......
function doSomeStuff( theNestedJsonArray )
{
// Traverse the array of Towns and show their latitude and longitude
for (var i = 0; i < theNestedJsonArray.length; i++)
{
var town = theNestedJsonArray[i];
var lat = town[1];
var long = town[2];
alert("The lat, long are: " + lat + ", " + long);
// ALL THIS WORKS FINE.
}
}
CASE #2 CODE -- REQUIRES AN EXTRA STEP, A CALL TO htmlentities( )
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
$theTopLevelArray= array();
for($i = 0; $i < $numrows; $i++)
{
$theRow = mysql_fetch_row($result);
$recordNum = $theRow[0];
$lat = $theRow[1];
$lng = $theRow[2];
$city = $theRow[3];
$state = $theRow[4];
// EACH NESTED ARRAY IS A TOWN with City, State, Latitude, Longitude
$nestedArray = array( $lat, $lng, $i, $recordNum, $city, $state);
$theTopLevelArray[] = $nestedArray;
}
$jsonArray = json_encode($theTopLevelArray);
$readyNowArray = htmlentities( $jsonArray );
// AND HERE'S THE 'body' ON MY PAGE:
<body onload="handleLoad( <?php echo $readyNowArray ?> )">
// HERE IS handleLoad()
function handleLoad( theNestedArray )
{
var town = theNestedArray[0];
alert("bl.js, handleLoad(), town is: " + town);
alert("bl.js, handleLoad(), town[0] is: " + town[0]);
alert("bl.js, handleLoad(), town[1] is: " + town[1]);
}
If I do not call html entities for CASE #2 -- the handleLoad() function does not even execute.
Is there some nuance here when echo'ing a PHP array in the body onload tag that is requiring the extra step of calling htmlentities() on the json array, while passing the json array directly into javascript from PHP code by way of an iframe is bypassing that somehow?

Is there some nuance here when echo'ing a PHP array in the body onload
tag that is requiring the extra step of calling htmlentities() on the
json array
Yes. You're echoing into HTML, for which you of course need htmlentities. If you don't, any quotes from the JSON will end your HTML onload attribute value, and the resulting js is nothing but a syntax error.
while passing the json array directly into javascript from PHP code
is bypassing that somehow?
Inside a <script>, nothing but </script> does need to be escaped.

Related

HTML collection getting parsed to JavaScript through PHP when it should be a String

I have a database that I use to create a resource of string values for example
|Boxers|1|
|Shirts|2|
etc
I then use php to populate a array with this resource
eg
$myArr = arrary['Boxers', '1', 'Shirts', 2]
then I parse the array as a JavaScript array through an echo and .push() each element within a for loop
This JS array then becomes the argument of a JS function call.
As you can see below.
<?php
if(isset($_SESSION["username"])){
$cartArr = array();
$sql = "SELECT item, quantity FROM shop_cart WHERE user = 'Mike'";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
array_push($cartArr,$row["item"],$row["quantity"]);
}
}
echo '<script> let paramArr = [];';
for($x = 0; $x < count($cartArr); $x++){
echo 'paramArr.push(' . "$cartArr[$x]" . ');';
}
echo 'cleanUpVue(paramArr);
</script>';
}
?>
The problem is that every element that is a String such as Boxers, Shirts keeps getting parsed as an HTML Collection and not just as a String. I'd like to know what I can do to avoid this behavior? As all I need is a JS array of String elements (4 as per the example) and nothing else
terrible what an obvious oversight on my part, I simply forgot to include quotation marks before concatenating the variable name, as such JS was trying to evaluate the original Strings as they also matched id's within the DOM
for($x = 0; $x < count($cartArr); $x++){
echo 'paramArr.push("' . $cartArr[$x] . '");';
}

Sending PHP array to JavaScript issue

I have an AJAX POST function that runs a PHP file that queries a MySQL database. It uses the "CONCAT" option in MySQL and then adds each row it receives into an array. I need to get that array from PHP to JavaScript, how would I go about doing this?
I've tried looking it up but nothing that I found either I didn't understand how to actually implement it, or it just flat out didn't work.
$sql_query = substr($sql, 0, -3);
$result = $connection->query($sql_query);
if (!$result) {
die("Invalid Query: " . mysqli_error());
}
$rowCount = mysqli_num_rows($result);
echo "Total Bans: " . $rowCount . "\r\n";
echo "\r\n";
$bans = [];
while ($row = $result->fetch_row()) {
for ($x = 0; $x < $rowCount; $x++) {
array_push($bans, $row[$x]);
}
}
I included that part of my PHP code if you need it.
I tried this:
echo(json_encode($bans));
.
success: function(data) {
document.getElementById('outputtext').innerHTML = '';
var array = new Array();
array = data;
document.getElementById('outputtext').innerHTML = array;
}
That returns everything, but adds a lot of "," between them.
Example of an index in the array:
[05-18] Daedalus banned EXAMPLE_USERNAME(EXAMPLE_GUID / EXAMPLE_IP) for EXAMPLE_REASON
I want all the lines from the $bans array to be put into an array in JavaScript.
When you usage echo(json_encode($bans)); that convert php array to json array. To use json in javascript you should first Parse that array like this
success : function(data){
result = JSON.parse(data) ;
}
Now you check this data console.log(result);
Access particular data through key like this
name = result.name;
This place in your code is wrong:
while ($row = $result->fetch_row()) {
for ($x = 0; $x < $rowCount; $x++) {
array_push($bans, $row[$x]);
}
}
Because you cycle trough records with while and inside once more with for. Use only while:
while ($row = $result->fetch_row()) {
array_push($bans, $row);
}
Will pull all rows and without nulls.
In your case when you have only single column in your return from database you should use:
while ($row = $result->fetch_row()) {
array_push($bans, $row[0]);
}

What is the best way to Parse a PHP Array into Javascript?

I currently have a PHP file that accesses my MySQL database and pulls out the Names and Scores for each player and stores them in an array.
//This query grabs the top 10 scores, sorting by score and timestamp.
$query = "SELECT * FROM Score ORDER by score DESC, ts ASC LIMIT 10";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
//We find our number of rows
$result_length = mysql_num_rows($result);
//And now iterate through our results
for($i = 0; $i < $result_length; $i++)
{
$row = mysql_fetch_array($result);
echo $row['name'] . "\t" . $row['score'] . "\n"; // And output them
}
What is the best way for me to get both the name and the score from the PHP File and store them in a Javascript Array?
The best way to store them is store them in json. Use following function
json_encode(arrayname);
and in html use
$.parsejson(responsevariable);
to get original value.
I would suggest to give json_encoded array to javascript variable (json_encode()), and use javascript json decoding functionality, so you will get what you want :)
Create a result variable
$results = array();
Store your results in it in your loop
array_push($results, array("name" => $row["name"], "score" => $row["score"]));
At the end return it with
echo json_encode($results);
When you get the response on the front end, you can take the response data and JSON.parse() it to turn it into a variable that you can access
var results = JSON.parse(data);
results.forEach(function(result){
console.log( result.name +" - "+ result.score );
});

HTML cannot see Javascript code; execution in php code breaks without error?

I'm trying to execute some PHP code, and then afterward use Javascript to take one of my PHP variables and use it to open a new window with that variable's contents on it in CSV format.
This works when my PHP variable is relatively small (i.e. 1,000 entries), but when I execute it on code that has for example about 20,000 entries in the array, it stops in the PHP code below without throwing any errors. What could be my issue? Yesterday I traced the issue to array_column - that the code would simply stop executing once it got to that line. However, it did it again today, even without that function and I gathered that there must be a bigger issue. I've re-included those array_column() calls since I assume they're not the real problem. Here's the PHP code:
function generateTextFile(){
$array = $_SESSION["array"];
$hostCol = array_column($array, "host");
$timeCol = array_column($array, "Time");
$col3 = array_column($array, "col3");
$col4 = array_column($array, "col4");
$signalCol = array_column($array, "Signal");
for($x = 0; $x < count($timeCol); $x++){
if(!isset($array[$x]["host"])){
$hostCol[$x] = $_GET['hostname'];
}
else{
$hostCol[$x] = $array[$x]["host"];
}
}
$subArray = array($hostCol, $timeCol, $col3, $col4, $signalCol);
$out = array();
foreach($subArray as $rowkey => $row){ // invert the array
foreach($row as $colkey => $col)
$out[$colkey][$rowkey] = $col;
}
$text = "";
for($x = 0; $x < count($out); $x++){
$curText = implode(",", $out[$x]);
$text = $text . $curText . "<br>";
}
$_SESSION['text'] = $text;
}
Is there something I'm doing wrong in the above PHP code? It just builds an array and then makes another variable in CSV format. I declared the script in the section of my HTML, after the above function is called. I'd be very grateful for your insight.
PHP have the thing called "time limit" to proccess the scripts.
The default is 30 seconds, and you can change this:
set_time_limit( int $seconds );
I had the same issue trying to proccess about 6.000 CSV's, and solved with this method.
Hope you find this useful!

PHP variable as Javascript variable name

I know this kind of post is frequently found on internet. But my problem is a little bit more dificult and I did not find an answer.
I want to make an associative array in Javascript in a loop with a variable name.
($JJ = table of object)
($JJ->getResto($DB,$acad) allows me to recover my database datas)
$JJ = new RestaU();
$JJ = $JJ->getResto($DB,$acad);
for ($i = 0; $i <= sizeof($JJ)-1; $i++) {
//Datas recovering
$lat = $JJ[$i]->loc_lat;
$long = $JJ[$i]->loc_long;
$name = $JJ[$i]->nom;
$ville = $JJ[$i]->ville;
//String treatment to avoid spaces
$ville = str_replace(" ","",$ville);
$name = str_replace(" ","",$name);
echo <<< SC
<script>
//here $ville will contain an google map object associated to the ville name.
//It means that I need to change it for each "for" loop.
var $ville = new Object();
//that is why here I need to have $ville["name"] to generate a table for each city
//and have an access to it later.
$ville+["name"] = new google.maps.LatLng($lat,$long);
console.log(string2);
</script>
SC;
My problem is, I can not find the solution to right for example ville1["name"]. Each time the code is not "interpreted" it means I can have the string but it does not create my array.
Thank you a lot for all your ideas!
SOLUTION IN COMMENT.
I used that :
var string = "$ville";
window[string]["name"] = "blabla";
It works really well.
php is server language and javascript is clint browser language!
in fact you can't share variables!
But you can print variables to javascript code like:
<script>
var myvar = '<?php echo $myvar; ?>';
</script>
if you want to send variables from javascript to php you must use Ajax
for array
<script>
<?php
$array = array('index1'=>'hellow World!','index2'=>'Iran haven`t nuclear bomb');
echo 'var arryname = new Array();';
foreach($array as $key=>$val){
echo "\n arryname['{$key}'] = '{$val}';";
}
?>
</script>

Categories

Resources