Storing PHP variable into JavaScript variable in a For loop - javascript

I know how to pass a PHP variable into JavaScript variable one by one, but now I wish to pass a bunch of variable in a For loop and I just stuck.
<?php
$m = new MongoClient();
$db = $m->data_from_tweeter;
$collection = $db->output;
$cursor = $collection->find();
foreach($cursor as $document){
echo $document['place'] ;
echo $document['fir'];
echo $document['sec'];
}
?>
I want to store 'place' as a String variable, 'fir' and 'sec' as two Num variables, and make them look like:
var num_1 {
some_place : some_fir,
some_place : some_fir,
some_place : some_fir,
....
}
and
var num_2 {
some_place : some_sec,
some_place : some_sec,
some_place : some_sec,
....
}
How can I make it? Thanks in advance!

if $document['fir'] and $document['sec'] are array .You can do like this
<?php
$m = new MongoClient();
$db = $m->data_from_tweeter;
$collection = $db->output;
$cursor = $collection->find();
$num1=array();
$num2=array();
foreach($cursor as $document){
echo $document['place'] ;
$num1 = json_encode ($document['fir']);
$num2 = json_encode ($document['sec']);
}
?>
You can use a JSON string as a object for javascript
var num_1 = <?php echo $num1;?>
var num_2 = <?php echo $num2;?>

The following code snippet might help get you started:
$num_1 = "var num_1 = {\n";
$num_2 = "var num_2 = {\n";
foreach ($cursor as $document) {
$num_1 .= " {$document['place']} : {$document['fir']},\n";
$num_2 .= " {$document['place']} : {$document['sec']},\n";
}
$num_1 .= "};\n";
$num_2 .= "};\n";
echo $num_1;
echo $num_2;

Related

Using variable on php to create another variable in JS

I'm having a hard time getting the value of a specific variable in php to use in js. This is my code in php:
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
}
?>
I want to get the value of this ($result['status']) and pass it on the variable pos in js. This is my js code:
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
var pos = $('PHP VARIABLE HERE').val();
alert(pos);
}
Thanks for your help.
The easiest way is to output it to javascript directly:
?>
<script type="text/javascript">
window.MY_PHP_VAR = <?php echo json_encode($myPhpVar); ?>;
</script>
...
window.MY_PHP_VAR now contains your php variable
if your javascript code is on same page where the result is comming then you can use this
var pos = `<?php echo $result['status'] ?>`;
var pos = `<?= $result['status'] ?>`;
===============
// refresh.php
===============
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
echo "<script> alert('". $result['status'] ."'); </script>";
/* If the $result['status'] is 'success' the above line will be converted to:
echo "<script> alert('success'); </script>";
*/
}
?>
so, every time the refresh.php loads, the script is going to get executed.
However, I suggest you to assign a id or class attribute to your h4 where you are echoing your status and access the value using the selectors in the javascript.
you could try giving an id or class to the status.
then in JavaScript you could then get the value of the id or class.
PHP
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<h4> <span class="status">' . $result['status'] . '</span></h4>';
}
?>
JavaScript
var oldStatus = '';
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
// note that since we used a class, you will get the value of the first element only.
var pos = $('.status').text(); // use .text() instead of .val()
if (pos.toLowerCase() == 'out' && pos != oldStatus){
oldStatus = pos;
alert(pos);
}
}

Pass PHP array from Javascript

I would like to pass a PHP array from JavaScript.
PHP Data Table
---------------------------
| adminID | adminEmail |
===========================
| 1 | abc#gmail.com |
| 2 | xyz#ymail.com |
===========================
Javascript
<script>
function checkuser_callback_function($el, value, callback) {
var $array = new Array("xyz#gmail.com","abc#ymail.com");
var valid = false;
if($array.indexOf(value) == -1){
valid = true;
}
callback({
value: value,
valid: valid,
message: "User present."
});
}
</script>
I want to pass that adminEmail here var $array = new Array("..","..");
I have tried alot in php but I didn't get any result.
<?php
include 'config.php';
$sql ="SELECT adminEmail FROM BEadmin";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)) {
$array = $row;
$str = "'" . implode ( "', '" ,$array ) . "'";
$parts = split("'", $str);
print_r($str);
}
?>
You can use php to create javascript array. Then use the same in the script later. Please note that , just to differentiate, I have called javascript array jArray instead of $array. Rest is explained along in the script only. Hope this helps..
<?php
include 'config.php';
$sql ="SELECT adminEmail FROM BEadmin";
$result = mysqli_query($con,$sql);
//start script tag
echo "<script>\n";
// javascript array decalaration beginning
echo "var jArray = new Array(";
$arrStr = "";
while($row = mysqli_fetch_assoc($result)) {
// $array = $row;
// $str = "'" . implode ( "', '" ,$array ) . "'";
// $parts = split("'", $str);
// print_r($str);
$arrStr .= '"'. $row["adminEmail"] . '",';
}
// drop the last , from the string
$arrStr = substr($arrStr,0,-1);
// now populate javascript array with this string
echo $arrStr;
// end javascript array
echo ");\n";
echo "</script>\n";
?>
<?php
include 'ePHP/config.php';
$sql ="SELECT adminEmail FROM BEadmin";
$result = mysqli_query($con,$sql);
$arrStr = "";
while($row = mysqli_fetch_assoc($result)) {
// $array = $row;
// $str = "'" . implode ( "', '" ,$array ) . "'";
// $parts = split("'", $str);
// print_r($str);
$arrStr .= '"'. $row["adminEmail"] . '",';
}
// drop the last , from the string
$arrStr = substr($arrStr,0,-1);
// now populate javascript array with this string
?>
<script>
function checkuser_callback_function($el, value, callback) {
var $array = Array(<?php echo $arrStr; ?>);
var valid = false;
if($array.indexOf(value) == -1){
valid = true;
}
callback({
value: value,
valid: valid,
message: "User present."
});
}
</script>

convert string into array for highcharts js

My code PHP generate a string variable
<?php
foreach($rows as $row){
$result .= "['" .$row["Name"]."'," .$row['Value']. "] , ";
}
$result = rtrim($result, ' , ');
//echo $result returns: ['FirstName1 LastName1',10] , ['FirstName2 LastName2',12] , ['FirstName3 LastName3 ',40]
?>
In js how can I convert the 'name' variable into a functional variable for 'data:' ?
<script>
var name = "<?php echo $result; ?>";
Highcharts.chart('container', {
...
data: [
['Shanghai', 23.7],
['Lagos', 16.1],
['Istanbul', 14.2]
];
...
});
</script>
Thank you!
You need to wrap $result in an array:
$result = "[$result]";
But you really should use json_encode like this:
$resultArr = [];
foreach ($rows as $row) {
$resultArr[] = [$row['Name'], $row['Value']];
}
$result = json_encode($resultArr);

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>

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

Categories