How do you automatically refresh part of a page automatically using AJAX? - javascript

$messages = $db->query("SELECT * FROM chatmessages ORDER BY datetime DESC, displayorderid DESC LIMIT 0,10");
while($message = $db->fetch_array($messages)) {
$oldmessages[] = $message['message'];
}
$oldmessages = array_reverse($oldmessages);
?>
<div id="chat">
<?php
for ($count = 0; $count < 9; $count++) {
echo $oldmessages[$count];
}
?>
<script language="javascript" type="text/javascript">
<!--
setInterval( "document.getElementById('chat').innerHTML='<NEW CONTENT OF #CHAT>'", 1000 );
-->
</script>
</div>
I'm trying to create a PHP chatroom script but I'm having a lot of trouble getting it to AutoRefresh
The content should automatically update to , how do you make it do that? I've been searching for almost an hour

I would take that PHP functionality you have and putting it in a sperate page that returns JSON. From there you can call that method using jQuery and the AJAX tools built in. Really simple. Start here for jQuery: http://api.jquery.com/category/ajax/

you'll need to set up a server side script that renders only the contents of the chat div and use ajax to grab that. it can be done with jquery quite easily:
In your html document:
<head>
...
<script src="/path/to/jquery.js" type="text/javascript"></script>
<script>
var chatUpdateInterval = null;
function initChat() {
chatUpdateInterval = window.setInterval(updateChat, 5000); /* every 5 seconds */
}
function updateChat() {
$.ajax({
url: '/url/path/to/your/script.php'
,dataType: 'HTML'
,success: function(data, status, xhr){
$('#chat').append($(data).html());
}
});
}
$(document).ready(function(){
initChat();
});
</script>
...
</head>
<body>
<div id="chat">
please stand by while we're firing up the coal!
</div>
</body>
Note that this won't be really good, it's just a sample to get you started. you should look into jquery's $.ajax

Related

Update page content from live PHP and Python output using Ajax

Long-time user, first-time asker. I've learned so much from the community and I love this site.
So here is what I'm shooting for. I want to have a web interface that runs ping commands on the backend. I ideally want a website that has a text input that allows you to enter an IP address or domain, a button that runs the command and a python script that runs from PHP to actually run the ping command. The tricky part for was to get the output to print to the website live as it is outputted on the command line. I want to do it this way as a way to future-proof the concept and eventually use different iperf parameters.
I built a little PHP page that "technically" gets the job done but I can't figure out how to only call the PHP script when the button is clicked. Since it's a PHP page, it runs whenever the page is loaded. So after some research, I figure ajax jquery is what I'm looking for. I've spent about 2 days trying different things that get me really close but it seems that I'm dancing around my solution.
From what I've learned about ajax, I essentially need a button that runs an ajax function that is linked to my working php script. I can get it to run the script but I can't get it to update the page content in a live/continuous manner. Only when the command is finished running.
Here is my php page that does what it needs to do but does it everytime the page is loaded/reloaded. Not ideal. I want the script to only run when the button is pressed.
liveping.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="liveping.php" id="ping" method="post" name="ping">
Domain/IP Address: <input name="domain" type="text"> <input name="ping" type="submit" value="Ping">
</form><?php
if (isset($_POST['ping'])) {
function liveExecuteCommand($cmd)
{
while (# ob_end_flush()); // end all output buffers if any
$proc = popen("$cmd 2>&1", 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
$live_output = fread($proc, 4096);
$complete_output = $complete_output . $live_output;
echo "<pre>$live_output</pre>";
# flush();
}
pclose($proc);
}
}
$domain = $_POST['domain'];
$pingCmd = "python /var/www/html/ping.py ".$domain;
if (isset($_POST['ping'])) {
liveExecuteCommand($pingCmd);
}
?>
</body>
</html>
ping.py:
#!/usr/bin/python
import cgi
import os
import sys
ping = "ping -c 5 -W 2 "+sys.argv[1]
os.system(ping)
Some things I've tried:
<html>
<head>
<script>
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = setInterval(function() {
if (ajax.readyState == 4) {
document.getElementById('content').innerHTML = ajax.responseText;
}
},100);
function updateText() {
ajax.open('GET', 'ajax.php');
ajax.send();
}
</script>
</head>
<body>
<button onclick="updateText()">Click Me</button>
<div id="content">Nothing here yet.</div>
</body>
</html>
OR
<!DOCTYPE html>
<html>
<body>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('ajax.php').fadeIn("slow");
}, 1000); // refresh every 10000 milliseconds
</script>
</head>
<div id="load_tweets"> </div>
</body>
</html>
WITH ajax.php
<?php
while (# ob_end_flush()); // end all output buffers if any
$proc = popen("ping -c 5 -W 2 google.com", 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
$live_output = fread($proc, 4096);
$complete_output = $complete_output . $live_output;
echo "<pre>$live_output</pre>";
# flush();
}
pclose($proc);
?>
Thanks for any help!
You do not need python for showing ping results. Just two PHP files will be enough.
index.php will have the AJAX functionalities along with the form.
ajax.php will have the code to ping specified domain address.
I afraid that using jQuery you might not able to catch the live feed. Because it doesn't have any onreadystatechange. So, you might need to use vanilla JavaScript in this case. Here is a working demonstration:
index.php:
<!DOCTYPE html>
<html>
<head>
<title>Ping AJAX</title>
</head>
<body>
<div>
Domain/IP Address: <input id="domain" type="text">
<input id="ping" type="button" value="Ping">
</div>
<div id="result"></div>
<script>
function updateText(domain) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState == 3) {
var old_value = document.getElementById("result").innerHTML;
document.getElementById("result").innerHTML = this.responseText;
}
};
var url = 'ajax.php?domain='+domain;
ajax.open('GET', url,true);
ajax.send();
}
document.getElementById("ping").onclick = function(){
domain = document.getElementById("domain").value;
updateText(domain);
}
</script>
</body>
</html>
ajax.php:
<?php
if (isset($_GET['domain'])) {
function liveExecuteCommand($cmd)
{
while (# ob_end_flush()); // end all output buffers if any
$proc = popen($cmd, 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
$live_output = fread($proc, 4096);
$complete_output = $complete_output . $live_output;
echo "<pre>$live_output</pre>";
# flush();
}
pclose($proc);
}
$domain = $_GET['domain'];
$pingCmd = "ping ".$domain;
liveExecuteCommand($pingCmd);
}
else{
echo "No post request";
}
?>
Output:
Declaimer:
The ping command is changed as I am currently using Windows operating system. Update it according to your operating system.
As a first time questioner, you have described the problem neatly and also showed your efforts to solve the problem. I really appreciate it.
ajax.readyState == 4
essentially means, script on the other side has finished ... 3 is partial.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
You just have to take all ajax script into the function
example:
function updateText() {
$.ajax({
type: 'GET', // can be POST, too
url: "ajax.php",
crossDomain: true,
data: {
firstvar: firstvar,
secondvar: secondvar
},
cache: false,
success: function(data) {
if($.trim(data) == "false") {
alert("Fail to recived data");
}
else {
// Success getting data
// Do some jobs
}
}
});
}
If you want to cancel submit to not refesh, U can use
return false; // At the end of the function above
Hope it helps.

Refresh the score automatically every 30 seconds through code and without 'Refresh' button

I have a index.php file where I am displaying cricket score:
<?php
error_reporting(0);
echo '<br/>';
$content=file_get_contents("http://cricscore-api.appspot.com/csa?id=1062576");
$array = json_decode($content,true);
echo $array[0]['de'];
header('Refresh:10;URL=index.php');
?>
<script type="text/javascript">
function getReply(data) {
document.getElementById("displayScore").innerHTML="";
document.getElementById("displayScore").innerHTML+=data.match+"<br/>";
document.getElementById("displayScore").innerHTML+=data.score+"<br/>";
document.getElementById("displayScore").innerHTML+=data.summary+"<br/>";
document.getElementById("displayScore").innerHTML+="Dt: "+data.date+"<br/>";
}
</script>
<script type="text/javascript" src="http://json-cricket.appspot.com/score.json?callback=getReply"></script>
I want the score to be refreshed automatically every 30 seconds through code without having any Refresh button in the page.
Can anyone please help? Thanks in advance
You can do something like this using Javascript to reload the page
<script type="text/javascript">
setTimeout(function() {
document.location = "http://YOUR_APP_URL";
}, 30000);
//other code as usual
</script>
If you want to make your app better you can use AJAX
you can use:
<script type="text/javascript">
setTimeout(function() {
location.reload();
}, 30000
);
</script>
or:
<meta http-equiv="refresh" content="30">
in your <head> tag
as Hari Lamichhane said If you want to make your app better you can use AJAX

How to add ajax execution time in boomrang page load time?

I am using boomerang plugin to check web performance.
Following the code that used to get page load time.
<script type="text/javascript" src="http://yui.yahooapis.com/combo?3.1.1/build/yui/yui-base-min.js&3.1.1/build/oop/oop-min.js&3.1.1/build/yui/yui-later-min.js&3.1.1/build/event-custom/event-custom-base-min.js&3.1.1/build/querystring/querystring-stringify-simple-min.js&3.1.1/build/io/io-base-min.js"></script>
<script src="/js/boomerang.js" type="text/javascript"></script>
<script src="/js/plugins/rt.js" type="text/javascript"></script>
<script src="/js/plugins/bw.js" type="text/javascript"></script>
<script src="/js/plugins/navtiming.js" type="text/javascript"></script>
<script type="text/javascript">
BOOMR.init({
BW: {
enabled: false,
cookie: 'HOWTO-BA'
},
RT: {
cookie: 'HOWTO-RT'
}
});
YUI().use("io-base", function(Y) {
var uri = "dynamic-content.txt?" + new Date().getTime();
var timer;
function complete(id, o) {
var html = "<p>\n" + o.responseText.replace(/^$/mg, '</p>\n<p>') + "\n</p>";
document.getElementById("dynamic-content").innerHTML = html;
if(timer) timer.loaded();
};
Y.on('io:complete', complete);
timer = BOOMR.requestStart("my-timer");
var request = Y.io(uri);
});
BOOMR.plugins.RT.setTimer("t_js", new Date().getTime() - t_pagestart).
startTimer("t_head");
</script>
script src="/pgr/js/howtos.js" type="text/javascript"></script>
<script type="text/javascript">
BOOMR.plugins.RT.endTimer("t_howtojs").endTimer("t_body");
</script>
Here YUI that make separate ajax call and adds execrutiont ime in page load time. In my website there are many ajax calls on page load, those execution time I want to add in page load time.
But stuck how to use YIU with existing code.
My ajax call
jQuery(document).ready(function($) {
$.ajax({
type : 'POST',
url : '/getdata/',
data : { sid:retSid},
dataType: 'JSON',
beforeSend: function(){
$('.blocker').show();
},
success : function(result) {
if(result.data)
{
....
}
});
});
You should use one of the SPA plugins to measure single page apps / AJAX apps. It would be better to ask your question on the boomerang support forum. We prefer keeping all discussion and issues in one place so that if a code change is required, we can reference the discussion via a git reference.
You can ask the question here: https://github.com/soasta/boomerang/issues

got error when using javascript ajax json to retrieve php array

My html page is suppose to retrieve the array from the php page and alert the first element in the array. But when I run the html, got the following error, "Uncaught TypeError: Object function (E,F){return new o.fn.init(E,F)} has no method 'parseJSON' " in the console window. I tried to use jQuery.parseJSON(json_data) instead of $.parseJSON(json_data) but still got the same error. How can I fix this?
script.js:
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array =jQuery.parseJSON(json_data);
var rec = data_array[0];
alert(rec);
alert("GOOD");
},
error: function() {
alert("BAD");
} });
}
newcal.html:
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8">
<link rel="stylesheet" media="screen" href="demo.css">
<body onload="getArr();">
<div id="rounded"><div id="main" class="container">
<div id="pageContent">
Hello, this is the default content
</div>
</div>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
</html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>
parseJSON was added in jQuery 1.4.1 (in 2010)
You are using jQuery 1.3.2 (from 2009), which is too old.
The current version of jQuery 1.x is 1.11 (released this year).
Use a more recent version of jQuery.
You should also tell the browser that you are sending it JSON instead of claiming that your JSON is HTML. (PHP defaults to claiming that anything it outputs through a web server is HTML)
<?php
header("Content-type: application/json");
$output = array("cat","dog");
echo json_encode($output);
?>
Then let jQuery parse it automatically:
success: function(data_array){
// Remove the following line. It will be parsed automatically.
// var data_array =jQuery.parseJSON(json_data);
var rec = data_array[0];

Next and previous button using jquery

I am using a PHP Simple HTML DOM Parser to save a website as a htm file. I then use jQuery to extract a div from the file and put it into a div. I want to create a
Previous and Next button but the problem I have is that to do this I have to change the URL so the parser can get the page. I would really appreciate if you can help. Below is the code I am using.
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=1');
$html->save('site/rtnews.htm')
?>
<script type="text/javascript" src="site/jquery.js"></script>
<script type="text/javascript">
$('document').ready(function() {
$('#wrap').click(function (event){
event.preventDefault();
});
$("#wrap").load('site/rtnews.htm #postsArea');
});
</script>
</head>
<body>
<div id="wrap">
</div>
</body>
You will have to create a new php file for this and make an AJAX request to that file. I assume you have already realised that you cannot make a cross-domain request due to CORS.
Here is your new php file, let's call it proxy.php. It will proxy the request, responding with the page that is passed to it via GET :
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=' . $_GET["page"]);
echo $html;
?>
Your new JavaScript;
$('document').ready(function() {
var $wrap = $('#wrap'),
page = 1;
$('#next').on('click', function () {
getPage(++page);
});
$('#prev').on('click', function () {
getPage(--page);
});
var getPage = function (page) {
$wrap.load('proxy.php?page=' + page + ' #postsArea');
};
getPage(page);
});

Categories

Resources