Pass PHP array to Javascript variable - javascript

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>

Related

How to pass php array value to javascript variable

I have working on core php, i have getting all values from database(select query) in this i have to executed while loop and changed to array variable after i have to pass that array value to javascript variable how to pass this please help.
here my code:
<?php
include "db_connection.php";
$locations=array();
$query = $conn->query('SELECT `pg_address` FROM `tbl_master_property` limit 10');
while ($row =$query->fetch_assoc()) {
$list[] = $row;
}
$locations=$list;
//echo "<pre>";print_r($locations);die;
//echo "<pre>";print_r($cart_info_json);die;
?>
<script type="text/javascript">
var geocoder;
var map;
var data = <?php echo json_encode($locations); ?>;
//console.log(data);
alert(data);
in this alert is showing (object,object,object,object,object,object,object,object)
try :
alert(JSON.stringify(data));
but i would recommend console.log(data); and debug in the console.

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>

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

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; ?>';

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