Set JS var with PHP var with AJAX - php

I have a php script that watches for the newest json file in a directory (below). Then in a javascript I parse and display the data from that file. The javascript reloads the data every x minutes.
I won't have the name of the file just that it will contain json data and to use the newest one.
The PHP script stores the most recent file stored in array fileList[0]. I want to pass that to the javascript without a full page refresh so I checked this stackoverflow post and found that an ajax call can be made to a php script but the example updates an element on the page.
Is there a way to update a javascript variable? I thought of maybe placing the filename as a hidden element and the grabbing before I refresh the data, but that seemed crude.
<?php
date_default_timezone_set('America/New_York');
$files = glob('json/*.*', GLOB_BRACE);
usort($files, 'filemtime_compare');
function filemtime_compare($a, $b)
{
return filemtime($b) - filemtime($a); // Order newest to oldest
}
$i = 0;
$show = 1; // Number of new files to show.
$fileList = array();
foreach($files as $file)
{
if($i == $show) break; else ++$i;
array_push($fileList, $file);
}
//echo $fileList[0] // DEBUG: Make sure I have the right file.
?>
AJAX:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
// This will send a request to a PHP page
$.ajax({
var jsonURL = "";
url: "phpDir.php",
dataType: "html",
success: function(data){
// Place the returned data into your content
}
jsonURL = $fileList[0];
});
</script>
</head>
<body>

To answer your question "Is there a way to update a javascript variable?"
You would do this:
var jsonURL = '';
function loadXMLDoc() {
// This will send a request to a PHP page
$.ajax({
url: "phpDir.php",
dataType: "JSON",
success: function(data){
jsonURL = data.url;
}
});
}
For ease of communication I have set the dataType to JSON. So PHP output would need to be json_encoded()ed:
<?php
$output = array('url' => $fileList[0]); // or whatever URL you want to return
echo json_encode($output);
?>

Related

How to add ID from PHP script to JavaScript code

I have a PHP script which Edit and Delete cars on my website. Now I want to make Edit and Delete buttons inside a dropdown, and I did but its adding dropdown just to the first car from the row, since the ID is the same for every dropdown. Now I know how to get the unique ID from every car from PHP but how can I achieve it in JavaScript. I will show you my code.
PHP:
$id = $row["id"];
<div class='dropdown'>
<button onclick='myFunction()' class='dropbtn'>Settings</button>
<div id='myDropdown".$id."'class='dropdown-content'>
".($featured!=1 ? "<a title='Make ".$title." Featured'href='forms/addfeatured.php?id=".$id."'>Make Featured</a>" : "<a title='Remove ".$title."' href='forms/removefeatured.php?id=".$id."'>Remove Featured</a>")."
<a title='Delete ".$title."' href='forms/deletecars.php?id=".$id."'>Delete</a>
</div>
JavaScript:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
So how can I have different ID in javascript so I can open dropdowns for each entry?
Only use , No need to technically learn AJAX or JSON !
You Just need to use the simple functions which has been prepared for use and has been put in the libraries. And set a few parameters that they need.
The important thing is that, You should know PHP runs on the server machine, not your browser or your PC.
So the PHP variables too.. They are not in your machine to easily put them in a JS variable.
At his point we need to communicate with the server to send them(using AJAX function) in a proper format(using JSON function) for us to use.
So, Your question :
How to add ID from PHP script to JavaScript code?
has the easiest solution just with these functions:
(At your browser page):
$.ajax({ .. some parameters .. });
$(document).ready(function() {
$.ajax({
type: 'post', //Transfer Protocol
url: 'serving.php', //Address of Server Page
dataType: 'json', //Data Structure
data: {action: 'demo'},
success: function(output) {
$variables = output;
}
});
});
and
(At your PHP page on the server)
json_encode(.. some data ..);
$variables = array("Chevy", "BMW", "Ford");
echo json_encode($variables ); // Encoded variable array
Unfortunately your codes and description are not clear for me to help directly in your project.
But I attach a simple practical Example :(in Jquery)
// carSelection.html page
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs
/jquery/2.1.1/jquery.min.js"> //jquery CDN
</script>
</head>
<body>
<div style="margin:2em">
<form id="myForm">
<select id="selectNumber">
<option>Choose a car</option>
</select>
</form>
</div>
<script>
var $cars = '';
$(document).ready(function() {
$.ajax({
type: 'post',
url: 'carServs.php',
dataType: 'json',
data: {action: 'demo'},
success: function(output) {
$cars = output;
var option = '';
for (var i=0;i<$cars.length;i++){
option += '<option value="'+ $cars[i] +
'">' +
$cars[i] + '</option>';
}
$('#selectNumber').append(option);
}
});
});
</script>
</body>
</html>
And
// carServs.php page
<?php
// ...
$cars = array("Chevy", "BMW", "Ford");
echo json_encode($cars);
//...
?>
just remeber to attach the jquery CDN at your code, In the head section or just before ending the body tag </body>
And if you insist to have it in JavaScript, It's possible just with a few changes in syntax.

Refresh php embedded in html [duplicate]

What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)

How to update the PHP current timestamp using jquery/javascript every second

I am working on the PHP cart timer script using PHP and jQuery/JavaScript.
I am iterating the set-interval function every seconds to get the PHP's current time-stamp.
When the first product is added to the cart, the timer begins before getting timer-stops it prompts the user, whether the user want to continue or cancel.
My code is follows
$(document).ready(function(){
var orderedtime = "echo $_SESSION['ordertime'];";
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}
else{
init();
}
});
var currenttime;
var alerttime;
var extratime;
function cd(){
alerttime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (1 * 60))); ?>"
extratime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (2 * 60))); ?>";
redo();
}
function redo(){
currenttime = "<?php echo date('h:i:s', time()); ?>";
if(alerttime == currenttime) {
//doing something
}
else if(currenttime == extratime){
//doing something
}
else{
cd = setTimeout("redo()",1000);
}
}
function init(){
cd();
}
The currenttime variable only storing the 1st iteration value is not getting updating.
How to solve this issue?
Please kindly help me to solve it.
Thanks in advance.
You're not actually requesting a time from the server in your setTimeout loop.
This line
currenttime = "<?php echo date('h:i:s', time()); ?>";
is set when the page is first generated and not changed again. If you want the time updated you need to send a request to the server. This probably isn't the best way to do it though.
Further to MikeW's excellent but incomplete answer, you need a way to request the time from the server and receive it back in the DOM.
There is only one way to do that: AJAX.
As Mike pointed out, the PHP code that you typed above only runs once: when the page is first generated. After the page has been generated and the document is "ready", you must use AJAX.
Below is a fully-working, copy/pastable example to demonstrate one way this could work.
Note that I had to over-ride the orderedtime variable because I don't know how/when you set that.
HTML/javascript side: index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
#timeDiv{width:40%;height:200px;background:wheat;padding:10px;}
</style>
<script type="text/javascript">
$(document).ready(function() {
//var orderedtime = "<?php echo $_SESSION['ordertime']; ?>";
var orderedtime = '';
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}else{
doAjax();
}
window.setInterval(function(){
doAjax();
},2000);
}); //END document.ready
function doAjax() {
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
}
});
}
</script>
</head>
<body>
<div id="timeDiv">
The time is: <span id="thetime"></span>
</div>
</body>
</html>
PHP side: get_the_time.php
<?php
if (isset($_POST['ordertime']) != true) {
$d = date("h:i:s");
}else{
$ot = $_POST['ordertime'];
$d = date('h:i:s', (strtotime($ot) + (1 * 60)));
}
echo $d;
IMPORTANT NOTE:
When using AJAX, the response sent from the server is received inside the success: function, and no where else.
If you later wish to use that data, assigning it into a variable inside the success function will not work. The best way I have found is to stick the received data into an element of some kind (a hidden input field works great for this), and then retrieve it from there when needed.
For example:
<input type="hidden" id="myHiddenField" />
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
$('#myHiddenField').val(myData);
}
});
Then, inside some other javascript function, you can grab that data and assign it to some variable, thus:
var someVar = $('#myHiddenField').val();
Hope this helps, late as it is.
This stackoverflow post has further information/explanation regarding AJAX. Check out the simplified AJAX examples at the bottom.

SImple Ajax Jquery with php & mysql query

i look this tutorial
http://tutorialzine.com/2009/09/simple-ajax-website-jquery/
but i don't understand how to make this work with php file with sql, echo ""; etc
If someone can explain, i try everything and nothing appears
Thanks :)
var default_content = "";
$(document).ready(function () {
checkURL();
$('ul li a').click(function (e) {
checkURL(this.hash);
});
//filling in the default content
default_content = $('#pagesContent').html();
setInterval("checkURL()", 250);
});
var lasturl = "";
function checkURL(hash) {
if (!hash) hash = window.location.hash;
if (hash != lasturl) {
lasturl = hash;
// FIX - if we've used the history buttons to return to the homepage,
// fill the pageContent with the default_content
if (hash == "")
$('#pagesContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url) {
url = url.replace('#page', '');
$('#loading').css('visibility', 'visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page=' + url,
dataType: "html",
success: function (data) {
if (parseInt(data) != 0) {
$('#pagesContent').html(data);
$('#loading').css('visibility', 'hidden');
}
}
});
}
load_page.php
<?php
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.php'))
echo file_get_contents('pages/page_'.$page.'.php');
else echo 'There is no such page!';
?>
demo.html
< a href="#page1">Page1< /a>
< a href="#page2">Page2< /a>
< a href="#page3">Page3< /a>
< a href="#page4">Page4< /a>
<div id="pageContent">
//loaded ajax page
</div>
in this scenario , link > index.html#page1 will load file 'pages/page_1.php'
but in main index.html just can load html code , not php syntax .
Can I use php command in this case ?
So it looks like the problem here is that in the tutorials example, they simply use an HTML file. For this, file_get_contents() will work fine. However if you want your server to parse PHP code before serving it to the user, you should use the include() function.
From the documentation :
The include statement includes and evaluates the specified file.
The file_get_contents() function behaves silghtly differently :
file_get_contents — Reads entire file into a string
It simply reads the contents of the file, the PHP code is not evaluated/executed/interpreted...

small prob with fetching data from text file

Update : success progress but still a problem : new data reloaded after refreshing the page twice it's ok to refresh the page once every 10 or 15 minutes but one ferfesh doesn't display the new data from the text file though it already contains the new data came from getData.php file
getData.php code
$connect = mysql_connect("localhost","root","");
$db = mysql_select_db("mydb",$connect);
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
$path = "text/";
$myfile = $path."data.txt";
$open = fopen($myfile,"w");
while($row = mysql_fetch_array($getTextR)){
$write = fwrite($open,"<div class='slide'><h1>".$row['id']."</h1><p>".$row['desc']."</p></div>");
}
$close = fclose($open);
mysql_close($connect);
index.php code
<script src="js/jquery-1.7.1.js"></script>
<script src="js/slides.min.jquery.js"></script>
<script>
$(function(){
$.ajax({
url: 'getData.php',
type: 'POST'
});
});
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "text/data.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) {
if (txtFile.status === 200) {
allText = txtFile.responseText;
}
}
}
txtFile.send(null);
});
</script>
html code
<div id="mydiv" class="slides_container">
<?php $path ="text/";
$open = fopen($path."data.txt","r");
$read = fread($open,50000);
$close = fclose($open);
echo $read;
?>
</div>
I would not have the php file write to a text file and then read the text file; you are doing two ajax calls / requests to the server where only one is needed.
Apart from that it could lead to errors on the server when two instances try to write at the same file at the same time.
If you change your getData.php to echo out the values instead of storing them in a text file, you can simplify your javascript to:
$("#myDiv").load("getData.php");
.ajax is asynchronous by default. If you call .ajax first and expect it to create the text file for the .load function that is called next on the same page, set async: false in the .ajax function.
$.ajax({
url: 'getData.php',
type: 'POST',
async: false
});
Also, might be helpful to add a delay to give your server time to write the text file if that becomes an issue. I don't know how big your text file may become. Example:
$("#myDiv").delay(1000).load("text/data.txt");
Or, in the succes function as jeroen suggested:
$.ajax({
url: 'getData.php',
type: 'POST',
success: function(){
$("#myDiv").load("text/data.txt");
}
});

Categories