PHP variable as Javascript variable name - javascript

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>

Related

Passing array data from php to javascript using a loop

Is there a similar way to implement this kind of "algorithm" in the right way?
for(i=0;i<howManyCourses;i++){
var stored = "<?php echo $buf[i] ?>";
var option = document.createElement("option");
option.text=stored;
e.add(option);
}
So I want to pass the data from the $buf array into a javascript variable. I've tried many ways but it seems like I cannot find the solution. I'm new into php and I apologise for any obvious mistake.
It should be in the same file or in another case AJAX will be the solution.
<script type="text/javascript">
const arr = <?php echo json_encode($buf); ?>;
for (var i = 0; i < arr.length ; i++) {
//do something
}
</script>
If you need that JS' variable buf contain the same elements as PHP's $buf, you can do the following:
var buf = <?php echo json_encode($buf); ?>;
Just keep in mind that if PHP's $buf is not an indexed array, JS' buf will be an object instead of an array.

Passing array to JS as values

I want to pass an array from PHP to Javascirpt so I just get a list of values - currently I get JSON format - which I know because I'm using JSON_ENCODE I'm just hoping/wondering is there a way to pass it as a simple set of values or to parse it afterwards?
Apologies I'm quite new to this :)
I've tried a few different things from previous answers to similar questions, but none seem to do the trick.
<?php
$user = 'xxx';
$pass = 'xxx';
$connection_string = 'connectionstringtomysqldatabase';
$connection = odbc_connect( $connection_string, $user, $pass );
$sqlstring = "SELECT FIELD1 FROM TABLE.ITEM where IASOHQ<>0 FETCH FIRST 10 ROWS ONLY";
$result = odbc_exec($connection, $sqlstring);
while ($info = odbc_fetch_array($result)) {
$content[] = $info;
}
?>
<script type="text/javascript">
var content = <?php echo json_encode($content); ?>;
</script>
I want...
var content = [68,116,49,57,13,11,46,47,14,79]
I get...
var content = [{"FIELD1":"68"},{"FIELD1":"116"},{"FIELD1":"49"},{"FIELD1":"57"},{"FIELD1":"13"},{"FIELD1":"11"},{"FIELD1":"46"},{"FIELD1":"47"},{"FIELD1":"14"},{"FIELD1":"79"}];
You are getting this result because your array is multi-dimensional with associative second level keys i.e. it looks like
$content = [['FIELD1' => 68], ['FIELD1' => 116], ..., ['FIELD1' => 79]];
This is because odbc_fetch_array returns an associative array for each row. To fix your data format, just change this line:
$content[] = $info;
to
$content[] = $info['FIELD1'];
That will give you an array that looks like your desired result of
[68,116,49,57,13,11,46,47,14,79]
Just add ' to make it a value. Change
var content = <?php echo json_encode($content); ?>;
to
var content = '<?php echo json_encode($content); ?>';
var myObject = JSON.parse(content);
Iterate over the array then.
Just change this peace of php code. I think that all of the index of array is FIELD1
...
while ($info = odbc_fetch_array($result)) {
$content[] = $info['FIELD1'];
}
...
Just
echo json_encode(array_values($content));
it will work;

Fetch 5 Columns and their value from Mysql query and translate into PHP

I am unable to find a simple and elegant solution to solve this after several tries.
In essence I would like a way to fetch the 5 fields taken from this query and assign them to PHP variables then latterly Javascript variables.
<?php
include_once('connect.php');
$result = mysqli_query($conn, " SELECT DISTINCT IPdestport as destport,COUNT(*) as count FROM PACKETSFORIP GROUP BY destport ORDER BY count DESC LIMIT 5;");
while($row[] = mysqli_fetch_array($result))
{
$destport1 = $row[1][ 'destport' ];
$destport2 = $row[2]['destport'];
$destport3 = $row[3]['destport'];
$destport4 = $row[4]['destport'];
$destport5 = $row[5]['destport'];
$count1 = $row[1]['count'];
$count2 = $row[2]['count'];
$count3 = $row[3]['count'];
$count4 = $row[4]['count'];
$count5 = $row[5]['count'];
}
?>
Here is more code of how I will eventually translate these PHP variables into Javascript variables in order to process them into a google chart
var destport1 = "<?php echo $destport1 ?>";
var destport2 = "<?php echo $destport2 ?>";
var destport3 = "<?php echo $destport3 ?>";
var destport4 = "<?php echo $destport4 ?>";
var destport5 = "<?php echo $destport5 ?>";
var count1 = "<?php echo $count1 ?>";
var count2 = "<?php echo $count2 ?>";
var count3 = "<?php echo $count3 ?>";
var count4 = "<?php echo $count4 ?>";
var count5 = "<?php echo $count5 ?>";
Any help would be very much appreciated. Thanks.
You can save a lot of repetitive code by using arrays.
To simplify the first step (assign them to PHP variables) just convert the result set into an array:
$destPorts = mysqli_fetch_all($result);
$destPorts will contain all of the rows from the result set. If you want to access the 'count' column of the second row, use:
$destPorts[1]['count']
Or to access the 'destport' column of the fourth row, use:
$destPorts[3]['destport']
Since the values are stored in the $destPorts array, there is no need to convert them into separate variables.
You can do something similar in JavaScript. Instead of creating separate variables, store the data in a JavaScript object:
var destPorts = <?php echo json_encode($destPorts); ?>
Now you can access the values stored in the destPorts JavaScript variable. To access the 'count' column of the second row, use:
destPorts[1].count
Or to access the 'destport' column of the fourth row, use:
destPorts[3].destport
When you store your result rows in arrays and objects instead of simple numerically indexed variables, your code is less repetitive and more flexible. You no longer need to know how many results are in the database; you can simply loop over the array or object and access all of the data.
For anyone searching for this in future this is the solution i eventually utilised. Found it in a previous web application i'd coded.
<?php
include_once('connect.php');
$result = mysqli_query($conn, " SELECT DISTINCT IPdestport as destport,COUNT(*) as count FROM PACKETSFORIP GROUP BY destport ORDER BY count DESC LIMIT 5;");
$portsarray = Array();
$countarray = Array();
while($row = mysqli_fetch_array($result))
{
$portarray[] = array('destport'=>$row['destport'], 'count'=>$row['count']);
echo $row['count'];
}
$portarray = json_encode($portarray);
?>
The above code fetches each port and the count of packets going to that port and this is latterly converted into javascript to be fed into a google chart, but i'll just show the part that fetches the PHP array and puts the variables contained within into javascript variables.
var obj = <?php echo $portarray; ?>;
for(var i= 0; i < obj.length; i++) {
var json = obj[i];
destport = json.destport;
numberofpackets = json.count;
destport = destport.toString();
numberofpackets= parseInt(numberofpackets);

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!

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

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.

Categories

Resources