Passing array to JS as values - javascript

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;

Related

Inserting PHP DB result into Javascript array

How can i insert PHP db result query to a javascript array. I have set of values in my Database and I want to get those values and store it in a javascript array. This is my query
$query = $db->query("SELECT * FROM members");
while ($row = $query->fetch_assoc()) {
echo $row['names'];
}
And I want to store it in a javascript array like this
var names = ['John','Chris','Leo'];
This is my code but im getting an error.
var names = [
<?php while ($row = $query->fetch_assoc()) {
echo $row['skill'];
} ?>
];
Do this instead.
$names = [];
<?php while ($row = $query->fetch_assoc()) {
$names[] = $row['skill'];
}
$javaScriptArray = json_encode($names);
?>
JavaScript is run on the browser while PHP is run on the server. They don't really integrate with each other. To make the array available in javascript do something like this.
<script>
var arr = <?php echo $javaScriptArray; ?>;
</script>

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);

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>

sort php json data in Javascript

I want to sort php json data from multidimensional array using javascript or jquery
my php is
$array = array();
$x = 0;
while($row = $get_images->fetch_assoc()){
$name = $row['name'];
$image_type = $row['image_type'];
$caption = stripslashes($row['caption']);
$arr = array('name' => $name, 'type' => $image_type, 'caption' => $caption);
$array[] = $arr;
//array_push($array, $$arr);
$x++;
}
echo json_encode($array);
the result looks like this:
[{"name":"2323dffd","type":"jpg","caption":"ddd"},{"name":"323232323","type":"jpg","caption":"dddfdf"},{"name":"dffdd","type":"jpg","caption":"dfdfdfere"}]
I want append the data to a document prefebly using a while loop in javascript but I am not sure how to use the data from the json file (I am not sure if it is valid). I tried some solutions such as $.each but they did not work. This is my JS:
$(function($){
$.getJSON("http://www.xxxxx.com/json.php", function(json) {
while(){
//your code here
$("#content").append(json...);
}
});
});
Not sure how your $.each() doesn't work, but this will work fine.
$.each(json, function(i,obj){
console.log(obj);
});
Where obj will be:
{"name":"2323dffd","type":"jpg","caption":"ddd"}
And you can do
console.log(obj.name);
and so on.
Further, here's a jsFiddle illustrating your JSON iteration.

How to get multidimensional array data using java script and php

I have a multidimensional array in php, and i want to get its data from javascript but i didn't work
here my code in php
$managername = $_SESSION['managername'];
$sqls = "select s.*,m.* from rm_allowedmanagers m inner join rm_services s on s.srvid = m.srvid where m.managername = '$managername' ";
$sql = mysql_query($sqls);
$newservices = array();
while($row = mysql_fetch_array($sql))
{
$nsrvid = $row['srvid'];
$nsrvname = $row['srvname'];
$nunitprice = $row['unitprice'];
$nunitpricetax = $row['unitpricetax'];
$ntotal = $nunitprice + $nunitpricetax;
$newservice = array($nsrvid, $nsrvname , $ntotal);
array_push ($newservices, $newservice);
}
and here my java script code
<script>
function changeserviceprice(id)
{
var newservice = $("#newservice").val();
var data = '<?= $newservices ?>';
var asd = data;
var asd2 = data[0][0];
$("#qq4").val(asd);
$("#qq5").val(asd2);
}
</script>
PHP code i think it is work fine, and i think the error is in javascript function.
when i try to print the data using javascript it print the "Array" word when i print the whole row "array", but
it print "a" character when i try to print the first element in the first array!!
try encoding the $newservices array:
var data = <?php echo json_encode($newservices); ?>;

Categories

Resources