I have two files php(index.php & data.php), the first send data to the second, and this it runs every one second and show the data.
The problem is the data is not updating
Maybe the code explains better
data.php
<?php
session_start();
$xml = simplexml_load_file("file.xml"); // the contents of the file changes every second
$json = json_encode($xml);
$_SESSION['varname'] = $json;
?>
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script language="JavaScript">
window.setInterval(function() {
<?php
session_start();
$json = $_SESSION['varname'];
?>
var newdata = <?php echo $json ; ?>;
//code to show data
}, 1000);
</script>
Thank you in advance
session_start must be called before any output (see notes in the documentation) which means you have to call session_start before any output:
<?php
session_start(); ?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script language="JavaScript">
window.setInterval(function() {
<?php
$json = $_SESSION['varname'];
?>
var newdata = <?php echo $json ; ?>;
//code to show data
}, 1000);
</script>
You are not actually calling your data.php script from your javascript at all. Your javascript is just static at this point (look at your output source), executing the same function over and over again with the same value for newdata. You need to actually make an AJAX call to the data.php script to update the JSON.
Note that the session_start comments on this thread are important. This should be fixed as well, but that will not solve the fundamental problem you area having of wanting to use javascript to pull in the updated JSON data, but not having the value of newdata change because it is currently just static on your page.
Related
What Im trying to do: Display a loading gif or text... at the very least show a black screen before and during the time the php is being executed.
What I have tried.
I have tested using flush () and I get nothing until the entire php process is finished. I dont particularly like this concept either but I'll take anything.
I am considering using two pages to accomplish this though the current project is nearly complete and would take some time to consolidate the scattered html/php code.
Currently I'm doing 3-simpleXML_load_file(), 1-include(), 1-file_get_contents()
I have javascript function plotting data from one of the simpleXML_Load_file()...
Im up for moving parts of the code to a different file but it's a big task. So id like some advise or suggestions on how to proceed.
If I need to elaborate more just ask!
Thanks,
JT
<html>
<head>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
?>
<script type="text/javascript">
<!--Plot function-->
$(function()
{
var d =
[
<?php
//Pulling in hourly data to plot temp vs time
$i=0;
$array=array();
while ($i<=100)
{
echo '['. (strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000) .','.$weather_hourly->data->parameters->temperature->value[$i] .'],';
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$value = (string) $value;
$min_sec_array[] = $value;
}
?>
</script>
</head>
<body>
<div id=graph>
</div>
</body
The main way you can accomplish this is by using AJAX and multiple pages. To accomplish this, the first page should not do any of the processing, just put the loading image here. Next, make an AJAX request, and once the request is finished, you can show the results on the page or redirect to a different page.
Example:
File 1 (jQuery must be included also), put this in the body along with the loader animation:
<script language="javascript" type="text/javascript">
$(function(){
var mydata = {};
$.post('/myajaxfile.php', mydata, function(resp){
// process response here or redirect page
}, 'json');
});
</script>
Update: Here is a more complete example based on your code. This has not been tested and needs to have the jQuery library included, but this should give you a good idea:
File 1: file1.html
</head>
<body>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
?>
<!-- Include jQuery here! Also have the loading animation here. -->
<script type="text/javascript">
$(function(){
$.get('/file2.php?Lat=<?php echo $lat; ?>&Lon=<?php echo $long; ?>', null, function(resp){
// resp will have the data from file2.php
console.log(resp);
console.log(resp['min_sec_array']);
console.log(resp['main']);
// here is where you will setup the graph
// with the data loaded
<!--Plot function-->
}, 'json');
});
</script>
<div id=graph>
</div>
</body
</html>
File 2: file2.php
I'm not sure if you needed the $min_sec_array, but I had this example return that as well as the main data you were using before.
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
//Pulling in hourly data to plot temp vs time
$i=0;
$main = array();
$array=array();
while ($i<=100)
{
$main[] = array((strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000), $weather_hourly->data->parameters->temperature->value[$i]);
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$min_sec_array[] = (string) $value;
}
echo json_encode(array(
'min_sec_array' =>$min_sec_array,
'main' => $main
));
exit();
?>
I would recommend not to do this with plain html and php if u expect it modify the page after it is loaded. Because php is server side processing, so it is executed before the page is send to the user. U need Javascript. Using Javascript will enable u to dynamically add or remove html elements to or from the DOM tree after the page was send to the user. It is executed by the users browser.
For easier start I would recommend jQuery, because there are lots of tutorials on such topics.
JQuery
JQuery learning center
A small example:
HTML
<head>
<meta charset="utf-8" />
<title> </title>
<script type="text/javascript" src="js/lib/jquery-1.9.1.js"></script>
</head>
<body>
<h1>Addition</h1>
<div id="error_msg"> </div>
<div id="content">
<!-- show loading image when opening the page -->
<img src="images/loading.gif"/>
</div>
<script type="text/javascript">
// your script to load content from php goes here
</script>
</body>
this will be nothing more then the following until now:
adding the following php file
<?php
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$result = $num1 + $num2;
echo '<p>Calculating '.$num1.' + '.$num2.' took a lot of time, but finally we were able to evaluate it to '.$result.'.</p>'
.'<p> '.$num1.' + '.$num2.' = '.$result.'</p>';
?>
wont change anything of the html, but adding javascript/ Jquery inside the HTML will be kind of connection between static html and server side php.
$(document).ready(function(){
$.ajax({ // call php script
url: 'php/script.php?num1=258&num2=121',
type:'GET',
timeout: 500,
contentType: 'html'
}).success(function(data){
// remove loading image and add content received from php
$('div#content').html(data);
}).error(function(jqXHR, textStatus, errorThrown){
// in case something went wrong, show error
$('div#error_msg').append('Sorry, something went wrong: ' + textStatus + ' (' + errorThrown + ')');
});
});
This will change your page to show the loading animation until the php script returns its data, like:
So you can setup the whole page in plain html, add some loading gifs, call several php scripts and change the content without reloading the page itself.
It is kind of nasty solution to your problem...
But this can work:
You work with those -
ob_start();
//printing done here...
ob_end_flush();
at the beginning you will create your rotating ajax gif...
Then you do all the processing and calculating you want...
At the end of the processing, just echo a small script that does a hide to your gif...
Depends on the exact need, maybe ajax can be more elegant solution.
In response to your conversation with David Constantine below, did you try using ob_flush()?
ob_start();
echo '<img src="pics/loading.gif">';
ob_flush();
// Do your processing here
ob_end_flush();
I think you don't have a problem with flushing your PHP output to the browser, but more likely with getting the browser to start rendering the partial html output. Unfortunately, browser behavior on partial html is browser-specific, so if you want something to work the same in any browser, the AJAX solution suggested in other answers is the better way to go.
But if you don't like that added complexity of a full AJAX solution, you can try to make your html output "nice" in the sense of providing some body output that can be formatted without needing the rest of the html output. This is were your sample code fails: It spends most of its time outputting data into a script tag inside the html header. The browser never even sees the start of the body until your PHP code has practically finished executing. If you first write your complete body, then add the script tag for the data there, you give the browser something to at least try to render whilst waiting for the final script to be completed.
I've found the same issue (albeit not in PHP) discussed here: Stack Overflow question "When do browsers start to render partially transmitted HTML?" In particular, the accepted answer there provides a fairly minimal non-AJAX example to display and hide a placeholder whilst the html file hasn't completely loaded yet.
I know this is an old question, but the answer provided in this page by rpnew is extremely clear and easy to adjust to your project's requirements.
It is a combination of AJAX and PHP.
The HTML page PHPAjax.html which calls the PHP script:
<html>
<head>
<script type="text/javascript">
document.write('<div id="loading">Loading...</div>');
//Ajax Function
function getHTTPObject()
{
var xmlhttp;
if (window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
}
else
{
xmlhttp = false;
}
if (window.XMLHttpRequest)
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction()
{
url='PHPScript.php';
http.open("GET",url, true);
http.onreadystatechange = function()
{
if (http.readyState == 4)
{
//Change the text when result comes.....
document.getElementById("content").innerHTML="http. responseText";
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
</html>
The Background PHP Script PHPScript.php:
<?php
sleep(10);
echo "I'm from PHP Script";
?>
Save both files in the same directory. From your browser open the HTML file. It will show 'Loading...' for 10 seconds and then you will see the message changing to "I'm from PHP Script".
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I have a question about using a php variable in my javascript file.
This is my index.php file:
<body>
<div class="container">
<div class="row">
<div class="span12">
<?php
if(isset($_GET['appid'])) {
// GET appid
$appid = $_GET['appid'];
$json_url ='http://api.url.com/api/gateway/call/1.4/getApp?appid=' . $appid;
$ch = curl_init($json_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$str = curl_exec($ch);
curl_close($ch);
$data = json_decode($str);
$array = json_encode($data);
}
else{
}
?>
<p id="errors" class="text-error"></p>
</div>
</div>
<hr>
</div> <!-- /container -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/main.js.php"></script>
</body>
As you can see I check if an appid is sent. When I received it I load data from an api.
In the bottom of the page I have a link to my javascript file. (.php because I want to use the php var $ array in my js file)
My main.js.php:
$(document).ready(function() {
var data = <?php echo $array;?>;
alert(data);
});
But I got always error in console:
Uncaught SyntaxError: Unexpected token <
Does anyone know what I do wrong?
You are creating the array in a completely different file! The two variables are not in the same scope. What's more, the Javascript file is apparently not interpreted as PHP (and neither should it). So:
Javascript complains about the <? tag, which it should never see.
Even if you solved that, it won't work since there's no PHP $array variable in main.js.php.
Start by understanding how Javascript and PHP are interpreted, see Reference: Why does the PHP code in my Javascript not work?.
Your variable is in a different scope since you're not using the PHP include function. Here's the easiest way I know to achieve what you want:
Rename your JavaScript file to main.js
Since you cannot use PHP in a .js file, declare your JavaScript variable before you call your script, like this:
<script type="text/javascript">
var array = '<?php echo $array ?>';
</script>
<script src="js/main.js"></script>
Then, in your main.js file, just replace the code you posted by this:
$(document).ready(function() {
var data = array;
alert(data);
});
Try this,
$(document).ready(function() {
var data = '<?php echo isset($array) ? $array :
json_encode(array("nothing in array data"));?>';
// if $array not set then it should return {"0":"nothing in array data"}
alert(data);
});
you forgot to Quote Value of var data use this
var data = '<?php echo $array;?>';
I'm using ajax to pass data to a php session in order to save the contents of a js powered shopping cart. Here is the test js code:
//js.html
<html>
<body>
<script>
function addCart(){
var brandName = $('iframe').contents().find('.section01a h2').text();
$.post("sessions.php", {"productName": brandName}, function(results) {
//success alert
});
}
</script>
</body>
</html>
and here is the php code:
//session.php
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
?>
<html>
<body>
<?php
//retrieve session data
echo "Product Name = ". $_SESSION['productName'];
?>
</body>
</html>
However what I need is after having saved the data to the session, I want to output it to the user in a mini cart in the sidebar.
When I run js.html it successfully passes the data to sessions.php. However the echo isn't displayed in js.html. If I run sessions.php then the echo displays but isn't in the page I need.
My question is, either via PHP or js, how do I then echo or display this data to the user on the page I need?
Thanks
Change session.php to this:
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
//retrieve session data
echo "Product Name = ". $_SESSION['productName'];
?>
And in your HTML code:
function addCart(){
var brandName = $('iframe').contents().find('.section01a h2').text();
$.post("sessions.php", {"name": brandName}, function(results) {
$('#SOME-ELEMENT').html(results);
});
}
$.post("sessions.php", {"productName": brandName}, function(results) {
alert(results.productName);
},"json");
//session.php
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
echo json_encode(array('productName' => $_SESSION['productName']);
?>
Using Pure Javascript
The echo isn't appearing because you're making an AJAX call. I don't see what's stopping you from outputting the details in the JS code, underneath where you make the Ajax request.
$.post("sessions.php", {"name": brandName}, function(results) {
//As in put the code here.
});
With the mootools Library
Alternatively, you can look into the mootools library. That library has a Request object, with an onSuccess method. You can port your shopping basket code into that onSuccess method.
I would like to set a PHP session without reloading the page when a user clicks a button. Ideally, the button click would immediately hide the div named download_div and would set the session "close_download" to true.
I understand that JS is user-side and that PHP is server-side, but I'm wondering if there is a way to blend the two worlds. Any ideas? Thanks!
<html>
<head>
<script>
function closeDownload()
{
$('.download_div').hide()
}
<?php
session_start();
$_SESSION['close_download'] = "true";
?>
</script>
</head>
<body>
Close
</body>
</html>
session.php
<?php
session_start();
$_SESSION['close_download'] = "true";
?>
download.html
<html>
<head>
<script>
function closeDownload()
{
$('.download_div').hide()
$.get("session.php")
}
</script>
</head>
<body>
Close
</body>
</html>
You have to use ajax, read the documents on jquery ajax calls, is the fastest way.
basically you have to have another php file that has this:
session_start();
$_SESSION['close_download'] = "true";
Then in your html/js you do something like $.get('newfile.php');
You can't put php in your javascript, but using ajax you can 'blend' them as u said
The way to blend the two worlds is - AJAX.
$.ajax({
url: "session.php",
data: {'name': 'test_session', 'value': 'foobar'}
}).done(function() {
$('#notification').html('Done!');
});
session.php-
<?php
session_start();
$name = $_POST['name'];
$value = $_POST['value'];
$_SESSION[$name] = $value;
?>
I got a syntax error on the following code. Once I took out the first line of code, the alert pops. My brain is almost dead and I can't find out why. Please help. Thanks a lot.
JS
var rss = <?php echo json_encode($test); ?>;
alert("Hello World");
Updated
html
<?php
$test=get_array();
//the $test is a multi-dimention array.
?>
<script type="text/javascript" src="js/slideshow.js"></script>
json_encode will return FALSE on failure, so if it fails, echo false will output nothing.
so your code became below, which give you a syntax error.
var rss = ;
alert("Hello World");
Edit:
From your updated edit, the reason is:
You can not write php code in a js file.
If you need that variable in the js file, assign it to a global variable first.
<script type="text/javascript">
var rss = <?php echo json_encode($test); ?>;
</script>
<script type="text/javascript" src="js/slideshow.js"></script>
To avoid error, your code should be:
var rss = <?php echo json_encode($test) ? json_encode($test) : "''"; ?>;
alert("Hello World");
Even if json_encode returns false, your code would be:
var rss = '';
alert("Hello World");
This is because JavaScript throws fatal error and stops current script execution because of:
var rss = <?php echo json_encode($test); ?>;
The problem is that this may return non-Valid JSON string and it throws new exception,
What you can do:
First of all you should determine if the string you got from PHP is actually valid.
As JSON methods usually do throw errors, you can simply put this var into try/catch block
try {
var rss = <?php echo json_encode($your_array); ?>;
} catch(e){
alert('Invalid JSON string');
}
In PHP, please also check if it's valid to prevent sending invalid JSON string back to javaScipt
In a .js file, PHP doesn't work. It will work only in files with extension .php .
Put your JS code in the PHP page; then it works.