echo PHP array in javascript - javascript

Answer from here : https://stackoverflow.com/a/12863675/894470 is how to assign array to variable.
I'm getting my data from php but when I echo it inside javscript like example below my chart wont draw.
var month_data= [<?php echo json_encode($lol); ?>];
but I can show alert and see all my data no problem like below:
If I copy the text from alert and paste it in array like below:
var month_data= [{month: '2014-01', KFC: 0, PizzaHut: 1},{month: '2014-03', KFC: 2, PizzaHut: 1},{month: '2014-04', KFC: 1, PizzaHut: 0},{month: '2014-05', KFC: 0, PizzaHut: 1},{month: '2014-07', KFC: 1, PizzaHut: 0},{month: '2014-10', KFC: 42, PizzaHut: 42}];
my chart will draw. What is wrong here??
UPDATE: My query:
$lol = array();
while ($row = mysqli_fetch_array($result)) {
$lol[] = "{month: '". $row['year'] ."-". $row['month'] ."', KFC: ". $row['kfc'] .", PizzaHut: ". $row['pizzahut'] ."}";
}
and I'm using Morris.js: http://morrisjs.github.io/morris.js/ to generate my chart.

You need a real PHP structure to encode it into JSON, not just a string:
$lol = array();
while ($row = mysqli_fetch_array($result)) {
$lol[] = Array(
"month" => $row['year'].'-'.$row['month'],
"KFC" => $row['kfc'],
"PizzaHut" => $row['pizzahut']
);
}
and:
var month_data = <?php echo json_encode($lol); ?>;
json_encode will automatically translate $lol into a json array containing objects (associative arrays are translated into objects).

All is fine, you just have to parse it to json format, you can do that using:
var month_data= JSON.parse('<?php echo json_encode($lol); ?>');
edit your php code like this:
$lol[] = array("month" => $row['year'], "KFC" => $row['kfc'] ...
anyway i do not recommend using php in js, the better way would be to put the content from the variable somewhere in html and than to take it with js.

Related

how to pass php array value to javascript without using JSON

I have a simple calculation from php database, which needs to be used in javascript, how to do it?
<script>
function check(){
var ramt=document.getElementByName('refundedamount[]');
var bal1=[];
<?php for each($balance1 as $val){
echo 'bal1.push('.$val.');';
} ?>
. . .
} </script>
<form onsubmit="return check()";
<?php
$balance1=array();
while($row=mysqli_fetch_assoc($result)){
$income=$row['totalincome'];
$exp=$row['totalexp'];
$balance=$income-$exp;
$balance1[]=$balance;
...... ?>
<input type="text" name="refundedamount[]"/>
</form>
How to use and read values of $balance1[] array into JAVASCRIPT. without using JSON. basically I want to cross check the value of php $balance1 array and input text array " refundedamount[]".
Without JSON, you can loop each value.
<?php
$balance1 = array( 1,2,3,4,5 );
?>
<script>
var balance1 = [];
<?php
foreach( $balance1 as $val ) {
echo 'balance1.push( ' . $val . ' );';
}
?>
console.log( balance1 );
</script>
Will result to
Array [ 1, 2, 3, 4, 5 ]
PHP side:
$arrayJSON = json_encode($balance1) to convert to JSON format.
JS side:
var array = JSON.parse("<?php echo $arrayJSON;?>");
Hope this help!
You can convert the php array into a javascript object then convert that object into an array, eg if it has numeric indices:
<script>
var obj = <?php echo json_encode($phpArray) ?>;
var arr = Object.keys(obj).map(function(k) { return obj[k] });
// Or if you're using ES6
var arr = Object.values(obj);
</script>

How can print a php array in javascript

I have an array $results and I need to use it inside my javascript part of the code. I tried json_encode() but it did not work..
Here is the code
<?php
//...
include realpath($_SERVER['DOCUMENT_ROOT'] . '/Classes/Controllers/ReportController.php');
$vaccRep= ReportController::getVacRep();
include realpath($_SERVER['DOCUMENT_ROOT'] . '/Classes/Controllers/VaccineController.php');
$names=VaccineController::getVCName();
?>
<canvas id="bar" height="195" width="250" style="width: 250px; height: 195px;"></canvas>
<script>
//THIS IS THE PART THAT WILL BE THE OTPUT OF THE QUERY
var barChartData = {
labels: <?php$obj=json_encode($names); var_dump($obj);?>,
datasets: [{
highlightFill: "#45668e",
highlightStroke: "#45668e",
fillColor : "#1ABC9C",
strokeColor : "#1ABC9C",
data: <?php $obj=json_encode($vaccRep); var_dump($obj);?>
}]
};
new Chart(document.getElementById("bar").getContext("2d")).Bar(barChartData);
<?php $obj=json_encode($vaccRep); var_dump($obj);?>
</script>
Simply echo the php array in js with json_encode(), like this :
$phpArray = array('name'=>'mani','email'=>'test#gmail.com','mobile'=>'123467890');
PHP array looks like this
Array
(
[name] => mani
[email] => test#gmail.com
[mobile] => 123467890
)
<script>
var jsArray = [];
var jsArray = <?php echo json_encode($phpArray);?>;
console.log(jsArray);
</script>
You will get this in your console
Object { name="mani", email="test#gmail.com", mobile="123467890"}
how about
<?php
echo "<script>";
echo "var $results = JSON.parse('" . json_encode($results) . "');";
echo "<script>";
?>
and then use $results in your javascript code anywhere but make sure this script block is loaded before you are using it.
You can try like this to print a php array in javascript
<?php
$abc=["a","b","c"];
?>
<script type="text/javascript">
var abc = "<?php echo (implode(',',$abc));?>";
var abcArr = abc.split(",");
console.log(abcArr);
</script>
You can simply use this code:
<?php
$array = ["a", 1, 2, "b,"];
echo "<script>";
echo "var data = ".json_encode($array).';';
echo "</script>";
?>
The output of this code will be:
<script>var data = ["a",1,2,"b,"];</script>, what will create correct javascript array.

csv to JSON not working

I have a csv file that I want transfer into JSON but it doesn't work the way I was hoping
PHP
$file = $_FILES['csv']['tmp_name'];
$csv= file_get_contents($file);
$array = array_map('str_getcsv', explode(";", $csv));
echo "<script type='text/javascript'>alert('OK!');</script>";
javascript
var myJsarray = <?= json_encode($array); ?>;
alert(myJsarray[0][0]);
my csv looks something like this
aaa;46
bbb;23
ccc;51
ddd;23
and my output looks like this
[["aaa"],["46\r\nbbb"],["23\r\nccc"],["51\r\nddd"],["23"]];
and I was hoping to get
[["aaa"],["46"],["bbb"],["23"],["ccc"],["51"],["ddd"],["23"]]
my idea was to put "$csv=explode("\n", $csv)" under "$csv= file_get_contents($file); "
But it gave me error that "$csv is not a string.
http://jdl-enterprises.co.uk/sof/25763045.php
If it's something like this that you want:
$csv= file_get_contents($file);
$array = explode("\r\n", $csv); // Update this to \n if need be or however you csv saves it
for($i=0;$i<count($array);$i++){
$array[$i] = explode(';', $array[$i]);
}
This will produce:
[["aaa","46"],["bbb","23"],["ccc","51"],["ddd","23"]]
And if you want it like your example, add into the code:
$array2 = array();
foreach($array as $ar) {
foreach($ar as $a) {
$array2[] = $a;
}
}
This will produce:
["aaa"],["46"],["bbb"],["23"],["ccc"],["51"],["ddd"],["23"]
Obviously there is a set of [ ] missing around the whole code, but you could stuff it all inside another array, or just add them manually.
Your "CSV" is in an incorrect format:
aaa;46 bbb;23 ccc;51 ddd;23
Change it to:
aaa,46 bbb,23 ccc,51 ddd,23
You do know there is a function just for reading CSV in PHP? It's called fgetcsv()
$data = array();
$fh = fopen('file.csv', 'r');
while (($line = fgetcsv($fh, 0, ';')) !== false) {
$data[] = $line;
}
fclose($fh);
echo json_encode($data);

How to format this Database record string into this JavaScript array of objects?

In a MySQL Database table column, I have a value like this returned to my PHP script...
position=1&x=0.203125&y=0.23125&position=2&x=0.8427083333333333&y=0.415625&position=3&x=0.5510416666666667&y=0.4375&
Broken down it looks like this...
position=1&
x=0.203125&
y=0.23125&
position=2&
x=0.8427083333333333&
y=0.415625&
position=3&
x=0.5510416666666667&
y=0.4375&
So this particular record has 3 sets of a position, x, and y
Now in my PHP script while I am in a while loop getting each row from the database, I need to take this column and break the string into seperate variables so that it can create this JavaScript from the above example database value I need to build this JavaScript value with my PHP...
<script>
$('#photo1 .avoid').addAnnotations(annotation, [
{x: 0.203125, y: 0.23125, position: 1},
{x: 0.8427083333333333, y: 0.415625, position: 2},
{x: 0.5510416666666667, y: 0.4375, position: 3}
]);
</script>
So each record/row in my database will have a column that has values like this and I need to build that little JavaScript snippets in my Loop for each row.
I would appreciate any help in how I can extract and get the data in that column to build this JavaScript?
If an absolute must, I can also alter how that data is stored in that database column if it needs to be separated differently or something to make it easier. I appreciate any help with this thank you.
Simple PHP loop example...
<?php
foreach ($rmaRecord as $rma){
$img1 = "
<script>
$(document).ready(function() {
$('#photo1 .avoid').addAnnotations(annotation, [
{x: 0.3875, y: 0.3246, position: 4},
{x: 0.8427083333333333, y: 0.415625, position: 2},
{x: 0.5510416666666667, y: 0.4375, position: 3}
]);
});
</script>";
}
As per my comment, if you could save the data as json, that would be easiest, but presuming you cannot, try the following:
$data = 'position=1&x=0.203125&y=0.23125&position=2&x=0.8427083333333333&y=0.415625&position=3&x=0.5510416666666667&y=0.4375&';
$json = array();
$pairs = array_filter(explode('&', $data));
for($i=0; $i < count($pairs); $i+=3){
$position = explode('=', $pairs[$i]);
$position = $position[1];
$x = explode('=', $pairs[$i+1]);
$x = $x[1];
$y = explode('=', $pairs[$i+2]);
$y = $y[1];
$json[]=array('x' => $x, 'y' => $y, 'position' => $position);
};
echo json_encode($json);
//echo '<pre>' . json_encode($json, JSON_PRETTY_PRINT) . '</pre>';
You are right that you need to split that string to an array and I think there are a number of ways to get that done. If your using a template style you can intersperse html with php. PHP is not my main strong point but as a quick and dirty solutions you can work with something like the folowing.
<script>
$(document).ready(function() {
$('#photo1 .avoid').addAnnotations(annotation, [
<?php
$a = "position=1&x=0.203125&y=0.23125&position=2&x=0.8427083333333333&y=0.415625&position=3&x=0.5510416666666667&y=0.4375&";
$a = preg_replace("/&$/","",$a);
$array = array_chunk(preg_split("/&/",$a),3);
$js_obj = "";
foreach ($array as $key) {
$js_obj .= "{" . $key[0] .",". $key[1] .",". $key[2] . "},";
}
echo preg_replace("/,$/","",$js_obj);
// Outputs {position=1,x=0.203125,y=0.23125},{position=2,x=0.8427083333333333,y=0.415625},{position=3,x=0.5510416666666667,y=0.4375}
?>
]);
});
</script>
Depending on your PHP version you could also try:
<script>
$(document).ready(function() {
$('#photo1 .avoid').addAnnotations(annotation, [
<?php
$a = "position=1&x=0.203125&y=0.23125&position=2&x=0.8427083333333333&y=0.415625&position=3&x=0.5510416666666667&y=0.4375&";
$a = preg_replace("/&$/","",$a);
$array = array_chunk(preg_split("/&/",$a),3);
echo json_encode($array, JSON_PRETTY_PRINT);
?>
]);
});
</script>

Inserting MySQL results from PHP into JavaScript Array

I'm trying to make a very simple autocomplete function on a private website using a trie in JavaScript. Problem is the examples I have seen and trying are just using a predefined list in a JavaScript array.
e.g. var arrayObjects = ["Dog","Cat","House","Mouse"];
What I want to do is retrieve MySQL results using PHP and put them into a JavaScript array.
This is what I have so far for the PHP (the JavaScript is fine just need to populate the array):
<?php
$mysqli = new mysqli('SERVER', 'U/NAME', 'P/WORD', 'DB');
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
while($stmt->fetch())
{
printf("%s, ", $name);
}
?>
Then I want to insert essentially each value using something like mysql_fetch_array ($name); (I know this is incorrect but just to show you guys what's going on in my head)
<script> -- this is the javascript part
(function() {
<?php while $stmt=mysql_fetch_array($name))
{
?>
var arrayObjects = [<?php stmt($name) ?>];
<?php }
?>
I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can't put them together.
In this case, what you're doing is looping through your result array, and each time you're printing out the line var arrayObjects = [<?php stmt($name) ?>];. However this doesn't convert between the PHP array you're getting as a result, and a javascript array.
Since you started doing it this way, you can do:
<?php
//bind to $name
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
</script>
Use json_encode to turn your PHP array into a valid javascript object. For example, if you've got the results from your database in a php array called $array:
var obj = "<?php echo json_encode($array); ?>";
You can now use obj in your javascript code
For the auto-completion you can use the <datalist> tag. This is a relatively new feature in HTML5 (see support table) but the polyfill exists.
Fill the <option> tags in php when building the page and you a are done.

Categories