Using variable on php to create another variable in JS - javascript

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

Related

Unexpected token when saving PHP variable in a Javascript variable

I have the following function on my Wordpress site to put a class on a ID when the date is correct. The problem is that a line break is created within the Javascript variable when it reads the file that you have previously created with the IDs.
function ProgramarBorrado(){
//Get day, month and year
$date = getdate();
$day = $date['mday'];
$month = $date['mon'];
$year = $date['year'];
//Create a list
$list = array();
//Open/create a file
$myfile = fopen("lista.txt", "w+");
//If true push an ID on a list
if(($day==5)&&($month==4)&&($year==2019)){
array_push($list,"#borrar22marc");
}
if(($day==5)&&($month==4)&&($year==2019)){
array_push($list,"#prova");
}
//For each value of the list, write in the file lista.txt
foreach ($list as $value) {
fwrite($myfile, $value."\n");
}
//Close write mode
fclose($myfile);
//Open read mode
$myfile = fopen("lista.txt", "r");
//Get the value of each line of the file
while(!feof($myfile)) {
?>
<script>
//Save the PHP variable on a JS variable
var simple = '<?php echo fgetss($myfile) ;?>';
console.log(simple);
//Add class with jQuery
jQuery(simple).addClass('borrar-programado');
</script>
<?php
}
}
add_action('wp_footer', 'ProgramarBorrado');
This is the error:
//Save the PHP variable on a JS variable
var simple = '#borrar22marc
';
Yes! trim function is the solution, thanks to 04FS for the solution, this is how the code is after the solution:
function ProgramarBorrado(){
//Get day, month and year
$date = getdate();
$day = $date['mday'];
$month = $date['mon'];
$year = $date['year'];
//Create a list
$list = array();
//Open/create a file
$myfile = fopen("lista.txt", "w+");
//If true push an ID on a list
if(($day==5)&&($month==4)&&($year==2019)){
array_push($list,"#borrar22marc");
}
if(($day==5)&&($month==4)&&($year==2019)){
array_push($list,"#prova");
}
//For each value of the list, write in the file lista.txt
foreach ($list as $value) {
fwrite($myfile, $value."\n");
}
//Close write mode
fclose($myfile);
//Open read mode
$myfile = fopen("lista.txt", "r");
//Get the value of each line of the file
while(!feof($myfile)) {
?>
<script>
//Save the PHP variable on a JS variable
var simple = '<?php echo trim(fgets($myfile)) ;?>';
console.log(simple);
//Add class with jQuery
jQuery(simple).addClass('borrar-programado');
</script>
<?php
}
}
add_action('wp_footer', 'ProgramarBorrado');

How to display values in JS from a PHP array that was posted from jQuery

I have a button called rename that when pushed, executes in jQuery a rename.php file. Inside that php file the program selects data from a mysql, creates an array with that data, and processes an array in to json_encode($array);. How can I then get that json encoded array and echo it out into javascript?
I'm trying to echo the array out so that javascript displays my images src's.
This is my second line of ajax so I just wrote the javascript out as if it were php because I'm not sure of the commands or structure in js.
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
/*alert(result);*/
document.getElementById("images_to_rename").innerHTML = foreach(jArray as array_values)
{
"<img src=\""array_values['original_path']"/"array_values['media']"/>";
}
}
}
);
and my jQuery php file:
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if(empty($_GET['image_name']))
{
echo '<div class="refto" id="refto">image_name is empty</div>';
}
else
{
echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach($_GET['image_name'] as $rowid_rename)
{
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE ".$username." SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arri[] = $row;
}
foreach($arri as $rows) //put them into workable variables
{
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
?>
<script type="text/javascript">
var jArray= <?php echo json_encode($arri); ?>;
</script>
<?php
}
echo "something2";
?>
My PHP file is a jQuery url:"test4.php", type: "GET", and is not the main file. The main file is called main.php and the test4.php is something that's called in jQuery when the user clicks on rename.
Somebody suggested console log so here's what chrome says:
<div class="refto" id="refto">image_name is not empty</div>[{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}] <script type="text/javascript">
var jArray= [{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}];
</script>
something2
Your ajax php file isn't render in browser, then the variable jArray is undefined. With your case, let return php file to json and you can get it as variable in result.
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if (empty($_GET['image_name'])) {
//echo '<div class="refto" id="refto">image_name is empty</div>';
} else {
//echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach ($_GET['image_name'] as $rowid_rename) {
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE " . $username . " SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$arri[] = $row;
}
foreach ($arri as $rows) { //put them into workable variables
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
//stop render here
die();
}
?>
php file need return only json string. Then we'll get result as json variable in javascript.
And Js:
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
var jArray = JSON.parse(result);
/*alert(result);*/
var txt = "";
jArray.forEach(function(array_values){
txt += `<img src=\""array_values.original_path."/"array_values.media"/>`;
})
document.getElementById("images_to_rename").innerHTML = txt;
}
}
);

Potentially wrong mySQL query making form buttons disappear

<script type="text/javascript">
function on_callPhp1()
{
var result = "<?php php_func();?>";
document.getElementById('phptext').innerHTML = result;
}
</script>
<form action="" method="POST">
<input type="button" value="Get Numbers" onclick="on_callPhp1()"/>
</form>
<div id="phptext"></div>
<?php
include_once ('/var/www/db/connection.php');
function php_func() {
for ($i = 0; $i <= 25000; $i++) {
$num = (rand(1,1000));
echo "Number #" .$i . "\t ------ " . $num;
echo "<br>";
$queryInsertNum = "INSERT INTO myDb.myTable(number) VALUES ('$num');";
$result = $mysqli -> query($queryInsertNum);
}
}
?>
Whenever I run the above code, I do not see the form button.
However, when I comment out the last line $result = $mysqli -> query($queryInsertNum); they appear and the page runs normally.
What could be wrong?
Update 1:
My connection.php is as follows
<?php
global $mysqli;
$mysqli = new mysqli("127.0.0.1", "user1", "somepassword", "myDB");
if ($mysqli -> connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli -> connect_errno . ") " . $mysqli -> connect_error;
}
?>
You have a variable scope issue , every php function has it's own scope, you cannot deal with a variable from outside the function within it unless you pass this variable to your function .
the $mysqli variable which we are talking about here .
and to solve this , you need either use global variables , which is considered as a bad practice, checkout this wiki for more details OR by passing your variable as a parameters as follows :
// hey `php_func` ,please pass $mysqli value to be able to use it within you
// or whatever the variable name is
function php_func($mysqli) {
for ($i = 0; $i <= 25000; $i++) {
$num = (rand(1,1000));
echo "Number #" .$i . "\t ------ " . $num;
echo "<br>";
$queryInsertNum = "INSERT INTO myDb.myTable(number) VALUES ('$num');";
$result = $mysqli -> query($queryInsertNum);
}
}
but take care, you will need every time you call your function to pass that variable to it as following :
php_func($mysqli);
this , will take us to the other issue , that you are mixing and misunderstanding the difference between client-side and server-side programming? ,
you are calling the php function like this :
var result = "<?php php_func();?>";
which is wrong , if you hit CTRL+U from your firefox you will figure out that the function already executed even before call your HTML event onclick
it's recommended in such a case -which you are need to open a contacting channel so to speak between the client side and server side- to use ajax
so , your script may be like this : here i will assume that your file name is phpfunc.php
the ajax part :
<script type="text/javascript">
function on_callPhp1()
{
$.ajax({
url: 'phpfunc.php?get=data', // change this to whatever your file is
type: 'GET',
success: function (data) {
document.getElementById('phptext').innerHTML = data;
}
});
}
</script>
<form action="" method="POST">
<input type="button" value="Get Numbers" onclick="on_callPhp1()"/>
</form>
<div id="phptext"></div>
<?php
function php_func($mysqli) {
for ($i = 0; $i <= 25000; $i++) {
$num = (rand(1,1000));
echo "Number #" .$i . "\t ------ " . $num;
echo "<br>";
$queryInsertNum = "INSERT INTO myDb.myTable(number) VALUES ('$num');";
$result = $mysqli -> query($queryInsertNum);
}
}
if (isset($_GET['get']) && $_GET['get'] == 'data') {
include_once ('/var/www/db/connection.php');
php_func($mysqli);
}
?>
I guess it 's because $mysqli is an unknow object inside your function, try to add global $mysqli inside your function.
<?php
include_once ('/var/www/db/connection.php');
function php_func() {
global $mysqli;
for ($i = 0; $i <= 25000; $i++) {
$num = (rand(1,1000));
echo "Number #" .$i . "\t ------ " . $num;
echo "<br>";
$queryInsertNum = "INSERT INTO myDb.myTable(number) VALUES ('$num');";
$result = $mysqli -> query($queryInsertNum);
}
}
?>

Change the value of external Javascript with PHP in foreach loop

How can I change the value of a js variable in a PHP foreach loop?
The js needs to be external.
This is a piece of the index.php here I want to get the output $prozent in the javascript, I don't know how to get a PHP variable to execute a js every time in a loop, the js is a chart. I get the chart in the loop in the echo'<div class="chart-wrapper"> with a this chart js.
<?php
$sql = //SQL query
$res = mysql_query($sql);
$i = 0;
$survey = array();
while ($row = mysql_fetch_assoc($res)) {
$survey[$i]['label'] = $row['Label'];
$i++;
}
foreach ($survey as $survey) {
echo '<div class="col-md-4">';
echo '<div class="front face">';
echo "<h3> ".$survey['label']."<br>";
$sql = //SQL Query
$res = mysql_query($sql) ;
$sql = //SQL Query
$resSum = mysql_query($sql) ;
while ($row = mysql_fetch_array($resSum)) {
$survey['ausgabe'] = $row['sum(a.answer)'];
}
$anzahlreihen = mysql_num_rows($res);
if ($anzahlreihen > 0) {
$prozent = $anzahlreihen * $survey['ausgabe'];
//bunch of ifelse statements
//This is the variable i want to get in the js
echo (round( $prozent, 2));
echo '</font>';
}
}
echo '</div>';
echo '<div class="back face center">';
echo'<div class="chart-wrapper">
}
There are two ways PHP and Javascript can interact.
Use AJAX to request a PHP script which returns JSON or have PHP output the following example HTML;
<script type="text/javascript">
var variable = value;
</script>

Passing a jscolor selection variable from jquery to php not working

I am using the jscolor.js function to display a colour picker. User selects a colour which is then fed into mysql for later usage. Problem is I can echo/alert the selected colour but it is not being passed to php. If I hard code it it works fine. Anyone have a suggestion on what I am missing.
<?php
include ('config.php');
$get_coords = mysqli_query($link, "SELECT * FROM color WHERE color_id = '1'");
while($row = mysqli_fetch_array($get_coords)) {
$color_id = $row['color_id'];
$color = $row['color'];
echo "<div style=color:#$color;>Select a color:</div> <input id='myField1'>";
}
?>
<script type="text/javascript">
$(document).ready(function() {
var myPicker = new jscolor.color(document.getElementById('myField1'), {});
myPicker.fromString('<?php echo $color; ?>');
$("#myField1").change(function() {
alert(myPicker);
$.post('updatecolor.php', { 'color': myPicker });
});
});
</script>
updatecolor.php
<?php
$link = mysqli_connect($db_host, $db_usr, $db_pass) or die("MySQL Error: " . mysqli_error());
mysqli_select_db($link, $db_name) or die("MySQL Error: " . mysqli_error());
$color=$_POST['color'];
$sql = "UPDATE color SET color = '$color' WHERE color_id = '1'";
mysqli_query($link, $sql) or die("Error updating Coords :".mysqli_error());
echo "success";
?>
All sorted now.
I've changed the PHP to:
echo "<div id='mypick' style=color:#$color;><h1>Select a color:</h1></div>";
And changed the JQuery to:
var myPicker = $("#myField1").val();
$.post('updatecolor.php', { color:myPicker });
document.getElementById('mypick').style.color = myPicker;

Categories