PHP / JS - Send values from php to a js array - javascript

I have a php array "$values", i want to transfer its values to a js array, which is working well, the only problem i'm getting is that it's making the 2 values sended stuck together as "onetwo" while i want them to be as two different values ["one","two"] in my Js array.
<?php
$values= ["one", "two"];
?>
<script>
var Js_array = [];
Js_array.push('<?php
for ($x = 0; $x < count($values); $x++) {
echo $values[$x];
}
?>');
alert(Js_array);
</script>
Thanks for your help.

You are currently echoing all the items of the php array into ONE instance of the Js_array.push() function, so Js_array.push adds all the items of your php array as 1 item into the javascript array.
You instead should invoke Js_array.push() on each item of the php array, so each item can be added to the javascript array seperately. The below code demonstrates the required modification:
<?php
$values = ["one", "two"];
?>
<script>
var Js_array = [];
<?php
for ($x = 0; $x < count($values); $x++) {
echo 'Js_array.push("'.$values[$x].'");'; // call Js_array.push on each item of php array;
}
?>;
alert(Js_array);
</script>

<?php
$values= ["one", "two"];
function addQuotes($each_value){
return "'".$each_value."'";
}
?>
<script>
var Js_array = [<?php echo implode(",",array_map("addQuotes",$values)); ?>];
alert(Js_array);
</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>

for loop to set javascript variable = to a php variable

I am working on a project that requires create hundreds of variables in javascript with PHP values. I can write each one line by line like so:
var M1 = <?php echo json_encode($$mn[0]); ?>;
var M2 = <?php echo json_encode($$mn[1]); ?>;
var M3 = <?php echo json_encode($$mn[2]); ?>;
As I said there are hundreds of these though and if it is possible to do in a loop I would be very interested in learning. I have searched all over and can't find a direct answer. It may very well be that this is not possible. I am new to coding and still learning what certain code can and cannot do.
Any insight or direction on this topic would be greatly appreciated!
If this is not an option is it possible to use an array index for the javascript variable name? I have created an array for the JS and PHP. The PHP works fine above but if I try to use an array index for the JS like below, it breaks:
var mcirc[0] = <?php echo json_encode($$mn[0]); ?>;
I have output the array and the values are coming up correctly but when I run this I get the message:
[object HTMLDivElement]
instead of the actually value that should show up.
UPDATE
$mn array:
for ($m1 = 1; $m1 < 6; $m1++) {
$mn[] = 'M'.$m1;
}
UPDATE
Select SQL creating array:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$$row["mcID"]= $row["mcName"];
}
The array for mcID looks like this:
M1 = "text1"
M2 = "text2"
M3 = "text3"
M4 = "text4"
M5 = "text5"
UPDATE
end result desired:
var M1 = "text1";
var M2 = "text2";
var M3 = "text3";
var M4 = "text4";
var M5 = "text5";
Where "text1, ...2, ...3, ...4, ...5" are coming from the MySQL database.
UPDATE
Here is the final code that got this working:
$sqlMC = "SELECT mcID, mcName FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$mcID[] = $row["mcID"];
$mcName[] = $row["mcName"];
}
<?php for ($m1 = 0; $m1 <5; $m1++) { ?>
var <?php echo $mcID[$m1]; ?> = <?php echo json_encode($mcName[$m1]); ?>;
<?php } ?>
Simply put JSON into variable
var json = <?php echo json_encode($$mn); ?>;
And then process the JSON way you want:
eg.
var json=[{key:someValue},
{key:someValue2},
{key:someValue3}
];
json.forEach(function(a){
console.log(a.key);
})
First in your query part, declare a variable to hold the result that you want. I'm assuming the M1 is mcID in your table and text1 is the mcName. For example:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
$mac = [];//or $mac = array(); Depends on your PHP version.
while($row = $result->fetch_assoc()) {
$mac[$row["mcID"]] = $row["mcName"];
}
And then, iterate through the $mac array with foreach loop. I'm assuming you are using PHP codes within HTML. The $key will be the mcID and the $value will be the mcName.
//php tag for the foreach opening
<?php foreach ($mac as $key => $value) { ?>
var <?php echo $key; ?> = <?php echo "'$value';"; ?>
//php tag for the foreach closing
<?php } ?>
OR, if you want to use javascript associative array.
var macJs = {};
<?php foreach ($mac as $key => $value) { ?>
macJs.<?php echo $key; ?> = <?php echo "'$value';"; ?>
<?php } ?>
And you can access the element like this in javascript macJs.M1.
You should use JSON to 'export' your objects/array through different languages, in that case:
var json = '<?= json_encode($your_array); ?>';
After this you can parse this Json, what should return your array:
var your_array = JSON.parse(json);

get MySql Data to PHP array and convert to Javascript array

I have mysql table like this
table = tbl_tst`
clm_num clm_amnt
1 - 25000
2 - 31700
5 - 52900
8 - 45000
I want to get that table data to php array like this
$temp = array([1,25000],[2,31700],[5,52900],[8,45000]);
After i'll convert php array into the javascript using this code
var jsArray = <? echo json_encode($temp); ?>;
Problem is when i run my code it's retrieve nothing. sometimes it's retrieving "Object" :(
This is my full php code
<?php
$con=mysql_connect("localhost","user","pass") or die("Failed to connect with database!!!!");
mysql_select_db("db", $con);
$query = "SELECT * FROM tblnum";
$result = mysql_query($query) or die(mysql_error());
$valueMap = array();
while($row = mysql_fetch_array($result)){
$valueMap[$row['clm_num'] & $row['clm_amnt']];
}
?>
<script>
var jsArray = <? echo json_encode($valueMap); ?>;
for(var i=0; i < jsArray .length; i++){
document.write("<li>"+jsArray [i]+"</li>");
}
</script>
Please help me to find this issue.
Thanks in advance!
You should enable PHP displaying errors, which would tell you there is an error while constructing your array.
<?php
## Turn on error reporting
error_reporting(-1);
ini_set('display_errors', 'On');
....
$valueMap = array();
while($row = mysql_fetch_assoc($result)){
$valueMap[$row['clm_num']] = $row['clm_amnt'];
}
?>
edit:
You requested a different sort of array I see:
while($row = mysql_fetch_assoc($result)){
$valueMap[] = array($row['clm_num'], $row['clm_amnt']);
}
MySQL is no longer maintained, please start using MySQLI or PDO http://rudiv.se/Development/Resource/when-to-use-mysql-vs-mysqli-vs-pdo-in-php
edit:
<?php
$temp = array(
array(1,2500),
array(2,31700)
);
?>
<ul id="list"></ul>
<script>
var json_array = <?php echo json_encode($temp, true);?>;
console.log(json_array);
var ul = document.getElementById("list");
for(i in json_array){
var li = document.createElement("li");
li.appendChild(document.createTextNode(json_array[i][0]+','+json_array[i][1]));
ul.appendChild(li);
}
</script>
First you have to check your php array is come or not. if it will be coming than use this code:
<script type='text/javascript'>
var js_data = <?php echo json_encode($valueMap); ?>;
var jsArray = js_data.toString().split(',');
for(var i=0; i < jsArray.length; i++){
alert(jsArray[i]);
}
</script>
This one for one array or one dimensional array like array['amount'].
i used this code for
$valueMap = array('25000','31700','52900','45000'); // php array
check this.
change this $valueMap[$row['clm_num'] & $row['clm_amnt']]; To $valueMap[] =array($row['clm_num'], $row['clm_amnt']);
$valueMap = array();
while($row = mysql_fetch_assoc($result)){
$valueMap[] =array($row['clm_num'], $row['clm_amnt']);
}
?>
<script>
var jsArray = <?php echo json_encode($temp); ?>;//change <? to <?php it's give error when sort tag is not enable
for(var i=0; i < jsArray .length; i++){
document.write("<li>"+jsArray [i]+"</li>");
}
</script>
//output
1,25000
2,31700
5,52900
8,45000
Try this:
while($row = mysql_fetch_array($result)){
$valueMap[$row['clm_num']] = $row['clm_amnt'];
}
And then in js:
for(var i in jsArray){
if (jsArray.hasOwnProperty(i)) {
document.write("<li>"+jsArray[i]+"</li>");
}
}

Categories