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');
Related
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);
}
}
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>
I have one login.php, one main.php, one functions_js.js and one functions_php.php (I use jquery too).
My problem is I need to take two variables from login.php and send it to functions_php.php (ajax, ok that works) but then in functions_php.php I make a query select (with this variables) and it returns me an array which I need on functions_js.js , in this file I have a function to insert images on main.php.
I don't know how to pass the array from functions_php to functions_js.js.
I've read that I can use json but I don't know how to use between 2 different files.
I've tried to use json and pass it to main.php but no works:
functions_php.php:
if (isset($_POST['user'])) {
function startPerson($nick,$pass){
$query = $conexion->query('SELECT archive_id FROM family WHERE family_id=(select distinct family_id from person where user_id = (select user_id from user where user_name="'.$nick.'" and password="'.$pass.'"))');
$query->execute();
while ($res = $query->fetch()) {
$id = $res['archive_id']; //archive_id
}
//coger las personas de las familias de ese archive_id
$query = $conexion->query('SELECT person_id, birth_date FROM person WHERE family_id in (select family_id from family where archive_id='.$id.')');
$query->execute();
while ($res = $query->fetch()) {
$person[] = $res[0]; //archive_id
$date[]=$res[1];
}
return array($person, $date);
}
header('Content-Type: application/json');
$encoded=json_encode(startPerson($_POST['user'],$_POST['pass']));
echo $encoded;
}
main.php:
<?php
$json_data=json_encode($encoded);
?>
<script>
var an_obj= <?php echo $json_data;?> ;
alert(an_obj);//returns null
</script>
function_js.js:
function startPerson (date) {
for(i=0;i=>date.length;i++){
var elem = date[i].split('-');
var mon= elem[1]; //month
var year=elem[0]; //year
var mont= num2mon(mon);
position(year,mont);
elem=" ";
mon=" ";
year=" ";
}
}
function position(year, mon)
{
$('#' + year + ' .' + mon).prepend('<img class="black_point" src="./images/circle.png"/>');
}
Have you tried changing:
var an_obj= <?php echo $json_data;?> ;
to:
var an_obj = "<?php echo $json_data;?>";
Remember, the variable is a string.
Can you also try doing an echo on $encoded?
Here is the actual file which i want to seperate the javascript from.
How do i tell the javascript where to look for the php file, at the moment i am only able to execute the javascript from within the php file..
<?php
date_default_timezone_set('Europe/London');
require_once("DbConnect.php");
$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist ORDER BY `date_played` DESC LIMIT 5 ";
$result = $db->query($sql);
$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist'] = $row->artist;
$lastplayed[$i]['title'] = $row->title;
$lastplayed[$i]['label'] = $row->label;
$lastplayed[$i]['albumyear'] = $row->albumyear;
$lastplayed[$i]['date_played'] = $row->date_played;
$lastplayed[$i]['duration'] = $row->duration;
$lastplayed[$i]['picture'] = $row->picture;
$i++;
}
$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime));
$lastplayedjson = json_encode( $lastplayed );
?>
i want this part to be in a separate file
<script type="text/javascript">
var lastplayedjson = <?php echo $lastplayedjson ?>;
alert( lastplayedjson[1].title );
alert( lastplayedjson[2].title );
alert( lastplayedjson[3].title );
alert( lastplayedjson[4].title );
</script>
You could include the first php file (we'll call it fileA.php) which would allow fileB.php to access all of it's variables
File A
<?php
$cats = 'topkek';
File B
<?php
include('/path/to/fileA.php');
echo $cats;
Should output
topkek
You can see here for the differences on include, require, include_once and require_once
in your php:
include_once('templates/template-name.php');
I am trying to create a PHP file that the browser will see as a js file, and are using the content-type header. But there's something not working, even though. So my question is, should this be interpreted as a valid .js file?:
<?php
header('Content-Type: application/javascript');
$mysql_host = "localhost";
$mysql_database = "lalalala";
$mysql_user = "lalalalal";
$mysql_password = "lalalallaala";
if (!mysql_connect($mysql_host, $mysql_user, $mysql_password))
die("Can't connect to database");
if (!mysql_select_db($mysql_database))
die("Can't select database");
mysql_query("SET NAMES 'utf8'");
?>
jQuery(document).ready(function() {
var urlsFinal = [
<?php
$result = mysql_query("SELECT * FROM offer_data ORDER BY id_campo DESC");
while($nt = mysql_fetch_array($result)) {
?>
"<?php echo $nt['url']; ?>",
<?php
};
?>
"oiasdoiajsdoiasdoiasjdioajsiodjaosdjiaoi.com"
];
scriptLoaded();
});
In order for your Browser to see your PHP file like a .js file, echo or print the entire PHP page into a string, there will be no need to use any headers, just something like:
// First let's make a secure page called database.php - put in a restricted folder
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
// now let's go over a new technique you'll cherish in the future - page.php
<?php
include 'restricted/database.php'; $db = db();
if($db->connect_errort)die("Can't connect to database. Error:".$db->connect_errno);
$db->query("UPDATE tabelName SET names='utf8' WHERE column='value'");
$sel = $db->query('SELECT * FROM offer_data ORDER BY id_campo DESC');
if($sel->num_rows > 0){
while($nt = $db->fetch_object()){
$output[] = $nt->url;
}
}
else{
die('No records were returned.')
}
$sel->free(); $out = implode("', '", $output); $db->close();
echo "jQuery(document).ready(function(){
var urlsFinal = ['$out'];
// more jQuery here - you may want to escape some jQuery \$ symbols
}"
?>
Now just make sure your script tag looks like:
<script type='text/javascript' src='page.php'></script>