how to pass php array value to javascript without using JSON - javascript

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>

Related

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>

converting with json_encode()

<?php
$array = array("first elem", "second elem");
?>
<html>
<head>
</head>
<body>
<script>
var js_array = '<?php echo json_encode($array); ?>';
for (var i = 0; i < js_array.length; i++)
{
document.write(js_array[i]);
document.write("<br>");
}
</script>
</body>
I have PHP array with two elements, when I converting this array to javascript array with json_encode()javascript divide my PHP array into set of chars, so in javascript array in a result i have a lot of elements. How to convert PHP array with two elements to javascript array with the same two elements?
You php function json_encode will give you a valid object, that's in fact what it means, JavaScript Object Notation.
So by using it as it is you will create an object in your JavaScript code. By enclosing it between apostrophes you are making it a string (who's value can be parsed as JSON).
So the simplest change would be to remove the apostrophes. So this line:
var js_array = '<?php echo json_encode($array); ?>';
Should become
var js_array = <?php echo json_encode($array); ?>;
The problem is that you have enclosed the json_encode in colons so you are converting it to a string. The javascript it produces is like this:
var js_array = '["first elem","second elem"]';
Here js_array is an string but you want an array. What you have to do is to produce the json directly as it will yield an array:
var js_array = <?php echo json_encode($array); ?>;
Replace you code with the following code..
<?php
$array = array("first elem", "second elem");
?>
<html>
<head>
</head>
<body>
<script>
var js_array = <?php echo json_encode($array); ?>;
for (var i = 0; i < js_array.length; i++)
{
document.write(js_array[i]);
document.write("<br>");
}
</script>
</body>
I hope its help you.....

Pass PHP array to Javascript variable

php file
$querySelectWordFilter = "SELECT * FROM badwordfilter";
$stmtSelectWordFilter = $conn->prepare($querySelectWordFilter);
$stmtSelectWordFilter->execute();
while($rowSelectWordFilter = $stmtSelectWordFilter->fetch()){
$Array[] = $rowSelectWordFilter["filterWord"];
}
foreach($Array as $val){
echo $val;
}
Javascript file
<script>
var filter = ['ass', 'evil','ugly'];
</script>
Question : Firstly,I select all the value from database and store it into array.But how can i pass the PHP array variable into JavaScript filter variable?
No need of foreach loop just create your array
while($rowSelectWordFilter = $stmtSelectWordFilter->fetch()){
$Array[] = $rowSelectWordFilter["filterWord"];
}
And in JavaScript use json_encode as
<script>
var filter = <?php echo json_encode($Array); ?>;
</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>

convert JS var to PHP and vice versa

Here I am getting values from textarea in array variable.
After that I convert javascript variable to PHP variable and perform some processing over it.
After process completed again I convert PHP to JS and alert. But when I alert, it gives empty result.
<script>
$( "#convert" ).click(function() {
var arabic = document.getElementById("ar").value; // ar is id of text area
<?php $ar_terms = "<script>document.write(arabic)</script>"?>
<?php
$string=implode(",",$ar_terms);
$result = array();
foreach ($ar_terms as $term) {
// echo $Arabic->ar2en($term);
array_push($result, $Arabic->ar2en($term));
}
$result=implode(",",$result);
?>
var arabic = new Array();
arabic='<?php echo $result; ?>';
alert(arabic);
});
</script>
Entire code is here : https://gist.github.com/karimkhanp/d4ac41fa864fd8ae0521
You can do one thing in this scenario to pass the variable from PHP to js. You can convert the array using json_encode() before echoing:
$result=json_encode( implode(",",$result) );
As a result, when you assign this variable to js in the <?= ?> block, it will read the json string and thus the array will be assigned:
arabic='<?php echo $result; ?>';

Categories