Automatically update with AJAX - javascript

I'm currently using this code on my webpage:
<?php
$url = "https://www.toontownrewritten.com/api/invasions";
$data = json_decode(file_get_contents($url));
if (!empty($data->invasions)) {
echo "<h1 style='text-align:center;margin:auto;padding:2px;font-size:16px;font-weight:bold;text-decoration:underline;padding:2px;'>Invasion Tracker</h1>";
$i = 0;
foreach($data->invasions as $title => $inv) {
print "<h3 style='text-align:center;margin:auto;'><b>District:</b> {$title}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Cog:</b> {$inv->type}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Progress:</b> {$inv->progress}
</h3>";
if (count(($data->invasions) > 1)) {
if (end($data->invasions) !== $inv) {
print "<hr>";
} else {
print "<br style='font-size:2px;'>";
}
}
}
} else {
echo "<h1 style='text-align:center;margin:auto;padding:2px;color:darkred;font-weight:bold;'>No invasions!</span>";
}
?>
I'm looking to make it refresh every 10 seconds via AJAX. However, I keep reading you need to make a function, but I'm not sure how I'd do that with the API? Every 10 seconds, that API is being updated, which is why I'd like this to be updated with AJAX every 10 seconds. Currently, I have it so the user has to manually refresh. Any help is appreciated!

You can simply reload the page with the method proposed here
But if you wanna have an AJAX implementation which just refereshes a part of your html nice and tidy, You gonna have to
Almost forget your PHP code
use the following code to implement the request to the url
$.ajax({
url: "https://www.toontownrewritten.com/api/invasions",
})
.done(function( data ) {
if ( console && console.log ) {
console.log( data );
}
});
Make a JS code which would convert the data got in the previous section to a readable html and show it on your page. It should be implemented in the the block where console.log(data) is.
Put that part of code in a setInterval
setInterval(function(){
//$.ajax();
}, 10000);
And be aware that you are gonna go to hell if your request doen't complete in the interval. see this .

I have a better suggestion, again it is same as using setInterval.
setInterval(function () {
if (isActive) return; // so that if any active ajax call is happening, don't go for one more ajax call
isActive = true;
try {
$.ajax("URL", params,function() { isActive = false;//successcallback }, function () {
isActive = false; // error callback
});
} catch (ex) { isActive = false;}
}, 10000);

Your problem is a failure to understand AJAX. Below is a $.post() example.
First let's make the page that you want your Client (the Browser user) to see:
viewed.php
<?php
$out = '';
// you could even do your initial query here, but don't have to
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<style type='text/css'>
#import 'whatever.css';
</style>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='whatever.js'></script>
</head>
<body>
<div id='output'><?php /* if initial query took place */ echo $out; ?></div>
</body>
</html>
Now you need your JavaScript in whatever.js.
$(function(){
function getData(){
$.post('whatever.php', function(data){
// var htm = do a bunch of stuff with the data Object, creating HTML
$('#output').html(htm);
});
}
getData(); // don't need if PHP query takes place on original page load
setInterval(getData, 10000); // query every 10 seconds
});
On whatever.php:
<?php
// $assocArray = run database queries so you can create an Associative Array that can be converted to JSON
echo json_encode($assocArray);
?>
The JSON generated by PHP shows up in the data argument, back in the JavaScript that created your PHP request:
$.post('whatever.php', function(data){

Related

AJAX progress bar of load script

I have a big problem to make a progress bar in AJAX. The whole page is in AJAX, inside one of the webpage is AJAX which loads a function to get some big rows from the database.
I tried to make progress bar in this script in a foreach loop a flush() method and by writing/reading to $_SESSION, but still nothing. I really tried everything I don`t know how to do this. Need only this to complete my project. Could someone help me with this?
It is anyway which script I want to load, how is the template for this progress bar to use it in GET or POST ajax, for any AJAX.
<script>
jQuery(document).ready(function($) {
$(document).on('click','#save',function () {
setTimeout(getProgress,1000);
$(this).text('Pobieram analizę...');
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
var id = $.urlParam('id');
var idt = $.urlParam('idt');
$.ajax({
url: "views/getresults.php?id="+id+"&idt="+idt,
success: function(data) {
$("#loadresults").append(data);
}
});
setTimeout(getProgress,3000);
return false;
});
function getProgress(){
$.ajax({
url: 'views/listen.php',
success: function(data) {
if(data<=100 && data>=0){
console.log(data);
$('#loadresults').html('<div id="progress"><div class="progress-bar" role="progressbar" style="width:'+ (data / 100)*100 +'%">'+ data + '/' +100+'</div></div>');
setTimeout(getProgress,1000);
console.log('Repeat');
} else {
$('#loadresults').text('Pobieram dane');
console.log('End');
}
}
});
}
});
</script>
and here is a getresults.php
foreach($result as $resul) {
$count++;
session_start();
$_SESSION['progress'] = $count;
$_SESSION['total'] = 100;
session_write_close();
sleep(1);
}
unset($_SESSION['progress']);
and a get progress function listen.php
<?php
session_start();
echo (!empty($_SESSION['progress']) ? $_SESSION['progress'] : '');
if (!empty($_SESSION['progress']) && $_SESSION['progress'] >= $_SESSION['total']) {
unset($_SESSION['progress']);
}
?>
Writing and reading session doesn't work because the standard behavior of PHP is to lock the session file while your main code is being executed.
Try to create a file and update the its content with the percentage done during the execution of your function. Something like:
<?php
function slowFunction() {
$file = uniqid();
file_put_contents($file, 0);
// Long while that makes your stuff
// you have to know how many loops you will make to calculate the progress
$total = 100;
$done = 0;
while($done < $total) {
$done++;
// You may want not to write to the file every time to minimize changes of being writing the file
// at the same time your ajax page is fetching it, i'll let it to you...
$progress = $done / $total;
file_put_contents($file, $progress);
}
unlink($file); // Remove your progress file
}
?>
You can't get the progress of the data download from ajax. Once you request you to the server, the next response will be only after fetching the data or when the error occurs.
The solution to you is, get the data as fractions. Such as first download the 1/10th of the data, and in the success callback, recursively call the ajax again requesting the 2/10th data. On each success callback, you could change the progress bar.
Take a look at Server Side Events or Long polling as options

Post Javascript to PHP and then retrieve in another javascript

I m trying to post the value from my java_post.js into php_post.php and then retrieve in another javascript page, index.html. So far i can post the value into the php_post.php and retrieve back into my java_post.js as alert(data)
but i cannot retrieve from my index.html
Java_post.js
var url_link ="index.html";
//On Click Select Function
$("#table_hot").on('click', 'tbody tr',function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
$.post('PHP_post/php_post.php',
{
postvalue:value
},
function(data){
alert(data);
}
);
});
//Window Pop Out Function
function hotspot_pop(url_link){
newwindow = window.open(url_link, '', "status=yes,
height=500; width=500; resizeable=no");
}
The value is retrieve when the client click the selected table and then post into the php_post.php. The php_post.php will filter the result and return to index.html.
$filtered_students = array_filter($ARRAY, function($row) {
$hotspot_value = $_POST['postvalue'];
if($row['name'] == $hotspot_value){
return true;
}
});
echo $filtered_students;
So now i m able to retrieve the value and post into as an alert for my java_post.js but the value is no pass into index.html and i receive the error for undefined postvalue.
<html>
<script src="js/jquery-1.11.1.min.js"></script>
<body>
<div id="result"></div>
<script>
var xmlhttp_user = new XMLHttpRequest();
var url_user = "PHP_post/php_post.php";
xmlhttp_user.onreadystatechange=function() {
if (xmlhttp_user.readyState == 4 && xmlhttp_user.status == 200) {
document.getElementById("result").innerHTML=xmlhttp_user.responseText; }
}
xmlhttp_user.open("GET", url_user, true);
xmlhttp_user.send();
</script>
</body>
</html>
So my problem is now, is there any method that allow me to show the value in index.html from php_post.php. As a reminder the alert(data) from java_post.js is just a testing purpose to show the value did post and return from php_post.php
The issue you're having is that when you pass the data into your PHP file and receive the data back in your JavaScript, the information only lasts as long as your current request.
To fix this issue, consider using PHP Session variables to store your data, so that you can retrieve it later.
Example:
// php_post.php
<?php
start_session(); // initializes session for persistent data
$filtered_students = array_filter($ARRAY, function($row) {
$hotspot_value = $_POST['postvalue'];
if($row['name'] == $hotspot_value){
return true;
}
});
$_SESSION["filtered_students"] = $filtered_students; // You can now retrieve this in
// Another PHP file
?>
Now in another file (you would switch your HTML file to get from php_get.php):
//php_get.php
<?php
start_session(); // Don't forget to start the session
echo $_SESSION['filtered_students'];
?>
More information here: http://www.w3schools.com/php/php_sessions.asp
You can set the desired value into PHP session while at php_post.php.
This way, you can retrieve the session's value on any page you desire.

php: make array from pictures in a folder and display them interchangeably?

The following code is supposed to make an array from pictures found in a directory that end in .png using php, then allow buttons to change the pointer on the array and allow the page to display the current picture that the pointer is on. This doesnt seem to be working at all. Am I doing this correctly?
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
img {float:left; }
</style>
</head>
<body>
<?PHP
$pages = array ();
$dirname = "assets/pictures/";
$images = glob($dirname."*.png");
foreach($images as $image) {
$pages[] = $image;
}
?>
<?PHP
echo '<img src="'.current($pages).'" class="photo"/>';
function shownext() {
$mode = next($pages);
}
function showprev() {
$mode = prev($pages);
}
function showfirst() {
$mode = reset($pages);
}
function showlast() {
$mode = end($pages);
}
?>
first
previous
next
last
</body>
</html>
onclick will allow you to call a javascript function, while your showprev...showlast functions are all php functions. They are not available in javascript's scope.
Also, in your php code:
You are closing the loop right after $pages[] = $image, I think you intend to display (print/echo) all images.
You don't need a loop to copy $pages to $images. You can easily copy it: $pages = $images.
You should be aware that current only makes sense inside a loop and you are calling it after loop is closed.
I think though, that you are confusing server-side (i.e. php) and client-side (i.e. javascript) execution environments.
onclick , uses to trigger javascript functions.
You cant directly put your php functions on onclick="" events. Alternatively, if you want to use jQuery, you could use $.ajax to request the values on PHP. From there, after you got the image paths, manipulate the next, prev, first, last on the client side. Consider this example:
<?php
if(isset($_POST['getimages'])) {
$dirname = "assets/pictures/";
$images = glob($dirname."*.png");
// collect the images
foreach($images as $image) {
$pages[] = $image;
}
echo json_encode($pages);
exit;
}
?>
<img src="" alt="" id="images" width="200" height="200" />
<br/>
First
Previous
Next
Last
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var current_pointer = 0;
var images = [];
$.ajax({
url: 'index.php', // call the php file that will process it, i just used this in the same page
type: 'POST',
dataType: 'JSON',
data: {getimages: true},
success: function(response) {
// after a successful response from PHP
// use that data and create your own array in javascript
images = response;
$('#images').attr('src', images[current_pointer]);
}
});
// simple pointer to navigate the array you got from PHP
$('a.navigate').on('click', function(){
var current_val = $(this).attr('id');
switch(current_val) {
case 'first':
current_pointer = 0;
break;
case 'last':
current_pointer = images.length-1;
break;
case 'next':
current_pointer = (current_pointer >= images.length-1) ? images.length-1 : current_pointer+1;
break;
case 'previous':
current_pointer = (current_pointer < 0) ? 0 : current_pointer-1;
break;
}
$('#images').attr('src', images[current_pointer]);
});
});
</script>
The problem is echo '<img src="'.current($pages).'" class="photo"/>';
This will get echoed once, no matter howoften you change $pages afterwards. You also can't call PHP functions with JavaScript's onclick.
PHP will generate the page on server side! On a fully laoded page, most interaction with the user is done via JavaScript.
To achieve your desired result, you have to export the array to JavaScript and change the image src via JavaScript, a little research will help you.

Retrieving JSON from PHP File, and Append inside div

Im trying to do near real time graph update within my site. To do this im trying to basically reload a php file every 30 seconds. I made the data of PHP dynamically echo out json code as shown below. Ad inside the file is also <meta http-equiv="refresh" content="30"> which refreshes the file to recheck database.
{"todayCalculateCR":"5%"}{"todayEPC":"0.20"}{"todayCTR":"34%"}{"yesterdayCalculateCR":"35%"}{"yesterdayEPC":"0.03"}{"yesterdayCTR":"24%"}{"monthCalculateCR":"14%"}{"monthEPC":"0.07"}{"monthCTR":"24%"}
Basically now i want some jquery code to place on my index.php page to load this file, interpret the json code and append the data to the correct divs.
Example:
<div class="yesterdayEPC">0.03</div>
Ive been looking on jquery.com and on stack overflow for ways to basically take the above json data and append it.
$.get( "dashboard-stats.php", function( data ) {
$( "body" )
.append( "yesterdayEPC: " + data.yesterdayEPC ) // John
.append( "Time: " + data.yesterdayEPC ); // 2pm
}, "json" );
This is brief of PHP file making json:
$month_visits = mysql_num_rows(mysql_query("SELECT * FROMlocker_reportsWHEREuid= '$user_id' ANDmonth= '$month_date'"));
$month_clicks = mysql_num_rows(mysql_query("SELECT * FROMreportsWHEREuid= '$user_id' ANDmonth= '$month_date' ANDstatus= '1'"));
$month_leads = mysql_num_rows(mysql_query("SELECT * FROMreportsWHEREuid= '$user_id' ANDmonth= '$month_date' ANDstatus= '2'"));
if($month_leads == "" || $month_clicks == "")
{
echo json_encode(array("monthCalculateCR"=>"n/a"));
echo json_encode(array("monthEPC"=>"n/a"));
}
else
{
$monthCalculateCR = number_format($month_clicks / $month_leads)."%";
echo json_encode(array("monthCalculateCR"=>"".$monthCalculateCR.""));
$monthEPC = number_format($month_leads / $month_clicks, 2)."";
echo json_encode(array("monthEPC"=>"".$monthEPC.""));
}
if($month_visits == "")
{
echo json_encode(array("monthCTR"=>"n/a"));
}
else
{
$monthCTR = number_format($month_clicks / $month_visits, 2) * 100 . "%";
echo json_encode(array("monthCTR"=>"".$monthCTR.""));
}
Try with the setTimeout function to call the $.get() jQuery method to recall the php file that echos the JSON.
reload();
function reload(){
$.get( "yourFile.php", function( data ) {
//update table based on data
var jsonData = $.parseJSON(data);
$('#myDiv').append('callback called').append(data);
});
setTimeout(reload, 30000);
}
I fixed my problem by basically making the json in 1 bracket.
Then using a tutorial I found out I can do below.
Todayclicks: <span id="clicks">
<script>
var JSONObject = {"todayEarnings":"2.60","todayVisits":"62","todayClicks":"26","todayLeads":"3","todayCalculateCR":"9%","todayEPC":"0.12","todayCTR":"42%","yesterdayEarnings":"0.40","yesterdayClicks":"35","yesterdayVisits":"148","yesterdayLeads":"1","yesterdayCalculateCR":"35%","yesterdayEPC":"0.03","yesterdayCTR":"24%","monthEarnings":"3.00","monthClicks":"65","monthVisits":"242","monthLeads":"4","monthCalculateCR":"16%","monthEPC":"0.06","monthCTR":"27%"}
document.getElementById("clicks").innerHTML=JSONObject.todayClicks;
</script>

Javascript/jquery .load passing variable

Stuck on a jquery/javascript function that is attempting to .load a set PHP script but passing get variable parameters. As an aside this is set to happen automatically after 5 seconds. New to posting here but have read a lot of posts and can't seem to find exactly what I am doing wrong.
This function works:
function LoadMyPhpScript()
{
$('#MyDiv').load('hello.php');
}
setTimeout(LoadMyPhpScript,5000);
This function does not work:
function LoadMyPhpScript2(cPhpParamString)
{
var strURL = 'hello.php';
strURL = strURL + cPhpParamString;
$('#MyDiv2').load(strURL);
}
setTimeout(LoadMyPhpScript2('?MyVar1=0&MyVar2=1'),5000);
Here's the hello.php
<?php
echo '<p>Hello, I am loaded with get values of MyVar1=' . $_GET['MyVar1'] . ', MyVar2=' . $_GET['MyVar2'] . '</p>';
?>
Note: this is just a mock-up, would use regex to validate gets, etc in production.
RESOLVED
Here is what I ended up with, thank you!
function LoadMyPhpScript1(cPhpParamString)
{
$('#MyDiv1').load('hello.php'+cPhpParamString);
}
setTimeout(function() { LoadMyPhpScript1('?MyVar1=0&MyVar2=1'); },5000);
When you do this:
LoadMyPhpScript2('?MyVar1=0&MyVar2=1')
You are executing the function and passing the result to setTimeout
Try this:
setTimeout(function() { LoadMyPhpScript2('?MyVar1=0&MyVar2=1'); },5000);
However, sending the url querystring like that is an odd way of doing it. Something like this might be better:
function LoadMyPhpScript2(myVar1, myVar2)
{
var strURL = 'hello.php';
$('#MyDiv2').load(strURL, { myVar1: myVar1, myVar2: myVar2 });
}
setTimeout(function() { LoadMyPhpScript2(0, 1); },5000);
Better try this way:
File help3.html:
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
function LoadMyPhpScript2(cPhpParamString)
{
var strURL = 'help3.php';
strURL = strURL + cPhpParamString;
$.ajax({
url: strURL
}).done(function(data) { // data what is sent back by the php page
$('#MyDiv').html(data); // display data
});
}
setTimeout(LoadMyPhpScript2('?MyVar1=0&MyVar2=1'),5000);
</script>
</head>
<body>
<div id="MyDiv">
</div>
</body>
</html>
File help3.php:
<?php
echo '<p>Hello, I am loaded with get values of MyVar1=' . $_GET['MyVar1'] . ', MyVar2=' . $_GET['MyVar2'] . '</p>';
?>
Test on my localhost, and both files on the same folder.

Categories

Resources