How can print a php array in javascript - 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.

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 to access PHP array element using JavaScript variable as key?

So I am trying to make a simple academic system.
I made dynamic boxes which show course information.
Core code looks like this
function addcourses(){ //(numcourses)
var num_courses= <?php echo $_GET['num']?>; //=numcourses
var newdiv;
var divIdName;
var i=0;
for(i=1;i<=num_courses;i++){
var divtoadd = document.getElementById('courselist');
newarticle = document.createElement('article');
divIdName = 'course'+i;
newarticle.setAttribute('id',divIdName);
newarticle.innerHTML ='<div class="box"><h2><?php echo $course_num_arr[i]?></h2><div class="content"><p>Credit Hours: <?php echo $credit_arr[0]?> </p><p>Professor: <?php echo $prof_arr[0]?></p><p>Average GPA: <?php echo $avg_arr[0]?></p><p>GPA: <?php echo $gpa_arr[0]?></p></div></div>';
call_course();
divtoadd.appendChild(newarticle);
}
}
The problem is with <?php echo $course_num_arr[i]?> since i is the variable from javascript, I don't know how to deal with this.
I want to echo $course_num_arr[1] when i = 1 and $course_num_arr[2] when i = 2 and so on.
If you don't want to use ajax call and wants to place the code in the PHP file, your can use json_encode() function. Please refer below code.
<?php
$cources = array( "0" => array ("name" => "maths","credits" => 30),"1"
=> array ("name" => "physics","credits" => 30));
?>
<script>
data=<?php echo json_encode($cources); ?>;
for(i=0;i<data.length;i++){
alert(data[i].name)
var h = document.createElement("H1");
var t = document.createTextNode(data[i].name);
h.appendChild(t);
document.body.appendChild(h);
}
</script>

How to create var javascript via php?

How to create var javascript via php ?
<?PHP
include("connect.php");
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words = $bad_words."".$resilt_row [word].",";
}
//echo $bad_words;
?>
<script>
var bad_words = ["<?PHP echo $bad_words; ?>"];
alert(bad_words);
</script>
I want to get var javascript like this var bad_words = ["fuck", "ass"];
When alert it's get only blank result.
How can i do that ?
<?php
include("connect.php");
$query = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
$badWords = [];
while($row = mysqli_fetch_array($query))
{
$badWords[] = $row['word'];
}
js
<script>
var bad_words = <?= json_encode($badWords); ?>;
alert(bad_words[0]);
console.log(bad_words);
</script>
I don't like gluing the strings if it's an array then pass it as an array with json_encode() function. Also in views it's better to use short syntax with <?= ?> tag
The string you're making is not the one you want.
You're not adding quotes.
Do this instead, using an array is better:
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
$bad_words = array();
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words[] = "'" . $resilt_row[word]. "'";
}
And then, down in your js:
var bad_words = ["<?php echo implode(",", $bad_words) ?>"];
or (for short)
var bad_words = ["<?= implode(",", $bad_words) ?>"];
If you want alert them as a string you can do it like this:
<script>
var bad_words = ["<?php echo implode('","',$bad_words); ?>"];
alert(bad_words);
</script>
Otherwise, you can print them as an array:
<script>
var bad_words = <?php echo json_encode($bad_words) ?>;
console.log(bad_words);
</script>
<?PHP
include("connect.php");
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words[] = $resilt_row['word'];
}
//echo $bad_words;
?>
<script>
var bad_words = ["<?php print implode('","',$bad_words); ?>"];
alert(bad_words);
</script>

Problems in passing PHP array to JavaScript

I understand that the format for passing a PHP array to Javascript is:
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
I have a php function that stores some values in a longitude and latitude array. These array do hold the right values within php since print_r() within php shows me that the array is correct.
print_r($latitude_array);
print_r($longitude_array);
Now, I pass on this array to JS in this manner:
<script>
var lati_array = "<?php echo json_encode($latitude_array); ?>";
var longi_array = "<?php echo json_encode($longitude_array); ?>";
alert(lati_array[0]);
</script>
In the beginning, when I open the HTML file, it shows me an empty array (which is expected because the PHP arrays aren't filled yet). Then user enters something, the php arrays are filled up with longitudes and latitudes. These values should now be passed to JS. However, it doesn't alert anything after that. I can't be sure if array is successfully passed to JS. What am I missing?
Try this:
<script>
var data = <?php echo json_encode( $data ); ?>;
</script>
Try like below:
<?php
$array_var = array(111, 222, 333, 444);
?>
<script>
var array_var = "<?php echo json_encode($array_var); ?>";
console.log(array_var);
array_var = JSON.parse(array_var);
console.log(array_var);
alert(array_var[0]);
</script>
You are getting a string in lati_array , Try to convert it into json like this:
<script>
var lati_array = "<?php echo !empty($latitude_array) ? json_encode($latitude_array) : ''; ?>";
var longi_array = "<?php echo !empty($longitude_array) ? json_encode($longitude_array) : ''; ?>";
lati_array = JSON.parse(lati_array);
alert(lati_array[0]);
</script>

Moving data from SQL database to an array in JavaScript via PHP

Ive been trying this for hours now but it wont quite get there.
I have a database which amongst other things contains geocodes, lat and lon. I have accessed these using the following PHP
<?php
mysql_connect("localhost", "tompublic", "public") or die(mysql_error());
mysql_select_db("first_section") or die(mysql_error());
$data = mysql_query("SELECT geo_lat, geo_lon FROM first_page_data")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data)){
$lat[] = $row['geo_lat'];
$lon[] = $row['geo_lon'];
}
?>
These values in $lat and $lon then need to be put into an array in a javascript function like so:
var latit = [];
var longi = [];
latit = '<?php echo $lat[]; ?>';
longi = '<?php echo $lon[]; ?>';
But it wont work! Any ideas?
Try:
var latit = <?php echo json_encode($lat); ?>;
var longi = <?php echo json_encode($lon); ?>;
Edit: Also, the mysql_ functions are deprecated.
You could try this:
var latit = [<?php echo implode(",",$lat) ?>];
var longi = [<?php echo implode(",",$lon) ?>];
First thing is first try to switch to MySQLi due to the fact that Mysql is depreciated.
But try
var latit = <?php echo json_encode($lat); ?>;
var longi = <?php echo json_encode($lon); ?>;
You can either do as #Robbert stated
OR
Using php json_encode convert it to JSON string and you need to JSON.parse() it to convert it to javascript object
var latit = JSON.parse("<?php echo json_encode($lat); ?>");
var longi = JSON.parse("<?php echo json_encode($lon); ?>");
JavaScript arrays are created using a comma separated list surrounded by brackets
var latit = [];
To use your PHP values
var latit = [<?PHP echo implode(",",$lat); ?>];
This assumes your values are numbers. If not, you'll need to include quotes.
var latit = ['<?PHP echo implode("','",$lat); ?>'];
Finally, json_encode is a good option as many of the other answers indicate.
Try this:
<?php
mysql_connect("localhost", "tompublic", "public") or die(mysql_error());
mysql_select_db("first_section") or die(mysql_error());
$data = mysql_query("SELECT geo_lat, geo_lon FROM first_page_data")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data)){
$lat[] = $row['geo_lat'];
$lon[] = $row['geo_lon'];
}
echo '
<script type="text/javascript">
var latit = '.json_encode($lat).';
var longi = '.json_encode($lon).';
</script>
';
?>

Categories