I'm creating a link-sharing website and on my index.php page (the page I want to refresh every 5 seconds) there are posts/links that must appear automatically (AJAX refreshing) without the user to refresh by him/herself or pressing F5 the whole time.
How would this work, precisely?
You should use the setInterval javascript function to deal with this issue.
setInterval(callServer, REFRESH_PERIOD_MILLIS);
See:
some info on ajax Periodic Refresh
javascript setInterval documentation
[edit] some good refresh examples, especially without js framework (depending wether you want to use jquery, mototools, another or no framework...)
you have to user the setInterval method to call your ajax function to inject new content into your div:
<HTML>
<HEAD>
<TITLE>Hello World Page</TITLE>
<script language="JavaScript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
// Mozilla/Safari
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq.overrideMimeType) {
xmlHttpReq.overrideMimeType('text/xml');
// See note below about this line
}
// IE
} else if (window.ActiveXObject) { // IE
try {
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xmlHttpReq) {
alert('ERROR AJAX:( Cannot create an XMLHTTP instance');
return false;
}
xmlHttpReq.open('GET', strURL, true);
xmlHttpReq.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
xmlHttpReq.onreadystatechange = function() {
callBackFunction(xmlHttpReq);
};
xmlHttpReq.send("");
}
function callBackFunction(http_request) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var responceString = http_request.responseText;
//TODO implement your function e.g.
document.getElementById("myDiv").InnerHTML+ = (responceString);
} else {
alert('ERROR: AJAX request status = ' + http_request.status);
}
}
}
setInterval("xmlhttpPost('test.php')", 5000);
</script>
</HEAD>
<BODY>
Hello World
<div id="myDiv"></div>
</BODY>
</HTML>
Is there a need to use AJAX?
Unless I'm missing something; you could use the meta refresh tag:
<meta http-equiv="refresh" content="5">
I would recommend increasing the time between refreshes as this will put a heavier load on the server and may cause to freeze, or slow down the site.
Use setInterval(myAjaxCallbackfunction,[time in ms]).
Callback uses property of js that function are first class members(can be assigned to variables), and can be passed as argument to function for later use.
Related
I have ajax that is communicating with php to receive tweets from a twitter account. The code is working fine.
The only thing is I want the ajax to intermittently call the php so that any updated tweets automatically come back and get printed to my page without having to refresh or re-enter a twitter id.
Do I need to keep calling the getStatuses() function or something?
Or do I need to use the getUpdates() which I have started to make somehow?
Here are my ajax functions:
// the setInterval function added in the getStatusesX function
function getStatusesX()
{
setInterval(getStatuses(),300000);
}
//Create a cross-browser XMLHttp Request object
function getXMLHttp() {
var xmlhttp;
if (window.ActiveXObject) {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
XMLHttp = new XMLHttpRequest();
} else {
alert("Your browser does not support XMLHTTP!");
}
return XMLHttp;
}
//function that searches for the tweets via php
function getStatuses(){
XMLHttp1 = getXMLHttp();
var userID = document.getElementById("userid").value;
//ajax call to a php file that will extract the tweets
XMLHttp1.open( 'GET', 'twitterTest2.php?userid='+userID, true);
// Process the data when the ajax object changes its state
XMLHttp1.onreadystatechange = function() {
if( XMLHttp1.readyState == 4 ) {
if( XMLHttp1.status ==200 ) { //no problem has been detected
document.getElementById("tweetbox").innerHTML=XMLHttp1.responseText;
}
}
}
XMLHttp1.send(null);
}
//function to intermittently call php to check for updated tweets?
function updateInfo() {
if(XMLHttp1.readyState == 4) {
document.getElementById("tweetbox").innerHTML=XMLHttp1.responseText;
}
}
</script>
I then added the getStatusesX() function to my form as follows:
<form>
Input Twitter ID: <input type="text" name="userid" id="userid">
<button type="button" onClick="getStatusesX()";>Get recent tweets</button>
</form>
It's still not working. Am i using the setInterval in the wrong way?
Use the setTimeout or setInterval functions.
From what I can see in your code, getStatuses has too much responsability since in addition of getting the data, it also modifies the DOM.
I would suggest something like:
function getStatuses(callback) {
//...
XMLHttp1.onreadystatechange = function () {
//...
callback && callback(XMLHttp1); //execute callback if any
};
}
function updateStatuses(callback) {
getStatuses(function (xhr) {
document.getElementById("tweetbox").innerHTML = xhr.responseText;
callback && callback;
});
}
//this function update the statuses and as soon as it's finished, it sets
//a timeout to redo the process in ~10 seconds.
function startUpdatingStatuses() {
updateStatuses(function () {
setTimeout(startUpdatingStatuses, 10000);
});
}
startUpdatingStatuses(); //kick-start everything
This question may have been asked a million times in the past but I am yet to come across a solution. So I ask again, hoping a less
aggressive answer like "Look somewhere else" or "Don't repeat
questions". If the reader feels the urge to type any of or similar to
the aforementioned sentences, I can only request the reader to refrain
from doing so and ignore this post completely. Any help is greatly
appreciated.
The problem
In my program, an AJAX script works to communicate with a PHP script. There are no syntax errors. The AJAX receives the responseText well and alerts it out.
alert(request.responseText); //this works as desired
But fails to return it to another function.
return(request.responseText); //this actually returns undefined
The full code
Client file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>test</title>
<script type="text/javascript" language="javascript" src="ajax.js"></script>
<script type="text/javascript" language="javascript">
function createXMLHttp()
{
var xmlHttp = null;
if(window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajax_phprequest(data, php_file)
{
var request = createXMLHttp();
request.open("POST", php_file, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
document.write(request.responseText);
return request.responseText; //changed from return(request.responseText;);
}
}
}
function foo()
{
alert(ajax_phprequest("user=defuser&pass=123456","auth.php"));
}
</script>
</head>
<input type="button" id="somebutton" value="Call foo()" onclick="foo();" />
<body>
</body>
</html>
The full code
auth.php file
<?php
$user;
$pass;
if (isset($_POST['user'])) $user = $_POST['user'];
else
{
echo 'err_u_Username is not specified';
exit();
}
if (isset($_POST['pass'])) $pass = $_POST['pass'];
else
{
echo 'err_p_Password is not specified';
exit();
}
if ($user = 'defuser' && $pass = '123456') echo ('That\'s right!');
else echo ('That\'s not right!');
?>
This can easily be solved by including the code in the same file as the document. But I wish to call the function from a different file and then return it to the file that has foo() or the document. Simply, I want the AJAX function to return the responseText without it giving an `undefined' every time. If this has anything to do with synchronization: I want to know of any workarounds against this problem.
The gist of it has already been mentioned, but I would like to go into a bit more depth as to why this doesn't work.
You have the following code:
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
document.write(request.responseText);
return(request.responseText);
}
}
Basically, you are setting the onreadystatechange event to the value of an anonymous function. In that anonymous function, you are returning a value, which won't be returned to the caller of ajax_phprequest(), but to the caller of the anonymous function, which is the event system and which doesn't care much about what value is returned.
This happens this way because it all happens asynchronously. In other words, you call ajax_phprequest() and all that happens at that moment happens behind the screens. The user can continue working like nothing has happened. However, in the background, the php file is requested and hopefully returned. When that happens, you get to use the contents, but the moment at which you called ajax_phprequest() has long since passed.
A proper way would be to use a callback function instead. It could look something like this:
function ajax_phprequest(data, php_file, callback)
{
var request = createXMLHttp();
request.open("POST", php_file, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
document.write(request.responseText);
callback(request.responseText);
}
}
}
function foo()
{
ajax_phprequest("user=defuser&pass=123456","auth.php", function (text)
{
alert(text);
});
}
That is because the call is ASYNCHRONOUS so you cannot return from stack the usual way, i.e. your alert(ajax_phprequest("user=defuser&pass=123456","auth.php")); is evaluated before the ajax response is returned ... you need to use a callback:
function callback( text ){
// something
}
...
if (request.readyState == 4){
callback( request.responseText );
}
im trying to get a bit of html to refresh every 1 second with AJAX, I made this code my self with bits from different websites that I found. Im trying to understand how it all works.
I want to be able to refresh the page without reloading it in the browser and I want the JS function AJAXdisplay(); to run every one second with the variables I send to AJAXreturn(); when I call it.
When I call AJAXreturn(); I want it to run AJAXdisplay(); once to print out the html from my php file, on my body if the index file I want somthing like this
<body onClick=:AJAXdisplay(same variables as used when the page was made);">
</body>
here is my code:
function getHTTPObject(){
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function AJAXsend(url) {
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("POST",url);
httpObject.send(null);
}
}
function AJAXreturn(url,pageName){
httpObject = getHTTPObject();
if (httpObject != null) {
if (navigator.appName != "Microsoft Internet Explorer") {
history.replaceState("", "", "index.php?page=" + pageName)
}
httpObject.open("POST",url);
httpObject.send(null);
AJAXdisplay(httpObject,url,pageName);
}
}
function AJAXdisplay(httpObjectIn,urlIn, pageNameIn){
httpObjectIn.onreadystatechange = function(){
if(httpObjectIn.readyState == 4){
document.getElementById('outputHTML').innerHTML = httpObjectIn.responseText;
AJAXdisplay('function(httpObjectIn,urlIn,pageNameIn)',1000);
}
}
}
To make javascript refresh, you should use the setInterval(); function. Here's what your looking for:
var timer = setInterval ("AJAXdisplay(variable);", 1000);
And if you ever need to stop the refresh you use:
clearInterval (timer);
I have a little script which uses AJAX and PHP to display an image. You can see below that if I call the function mom() it looks in the PHP file index.php?i=mom and displays the image I'm looking for.
But I need the javascript to be lighter as I have 30 images and for each one I have to modify and copy the script below. Is there not a simpler way to have the functions be different and still call a different page?
<script type="text/javascript">
function mom()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('mom').innerHTML = response;
}
</script>
My Trigger is this
<a href="#" onclick='mom();' />Mom</a>
<div id='mom'></div>
You could modify your function so it takes a parameter :
// The function receives the value it should pass to the server
function my_func(param)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
// Pass the received value to the handler
HandleResponse(param, xmlHttp.responseText);
}
}
// Send to the server the value that was passed as a parameter
xmlHttp.open("GET", "index.php?i=" + param, true);
xmlHttp.send(null);
}
And, of course, use that parameter in the second function :
function HandleResponse(param, response)
{
// The handler gets the param too -- and, so, knows where to inject the response
document.getElementById(param).innerHTML = response;
}
And modify your HTML so the function is called with the right parameter :
<!-- for this first call, you'll want the function to work on 'mom' -->
<a href="#" onclick="my_func('mom');" />Mom</a>
<div id='mom'></div>
<!-- for this secondcall, you'll want the function to work on 'blah' -->
<a href="#" onclick="my_func('blah');" />Blah</a>
<div id='blah'></div>
This should work (if I understand correctly)
<script type="text/javascript">
function func(imgName)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
document.getElementById(imgName).innerHTML =
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
</script>
MARTIN's solution will work perfectly.
By the way you should use some javascript framework for Ajax handling like jQuery.
It will make your life easy.
If you are having light weight images you preload the images on your page.
I solved this by making an array of in your case xmlHttp and a global variable, so it increments for each request. Then if you repeatedly make calls to the same thing (eg it returns online users, or, whatever) then you can actually resubmit using the same element of the array too.
Added example code:
To convert it to a reoccuring event, make a copy of these 2, and in the got data call, just resubmit using reget
var req_fifo=Array();
var eleID=Array();
var i=0;
function GetAsyncData(myid,url) {
eleID[i]=myid;
if (window.XMLHttpRequest)
{
req_fifo[i] = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req_fifo[i] = new ActiveXObject("Microsoft.XMLHTTP");
}
req_fifo[i].abort();
req_fifo[i].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(i);
req_fifo[i].open("GET", url, true);
req_fifo[i].send(null);
i++;
}
function GotAsyncData(id) {
if (req_fifo[id].readyState != 4 || req_fifo[id].status != 200) {
return;
}
document.getElementById(eleID[id]).innerHTML=
req_fifo[id].responseText;
req_fifo[id]=null;
eleID[id]=null;
return;
}
function reget(id) {
myid=eleID[id];
url=urlID[id];
req_fifo[id].abort();
req_fifo[id].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(id);
req_fifo[id].open("GET", url, true);
req_fifo[id].send(null);
}
The suggestions to parameterize your function are correct and would allow you to avoid repeating code.
the jQuery library is also worth considering. http://jquery.com
If you use jQuery, each ajax call would literally be this easy.
$('#mom').load('/index.php?i=mom');
And you could wrap it up as follows if you'd like, since you say you'll be using it many times (and that you want it done when a link is clicked)
function doAjax(imgForAjax) { $('#'+imgForAjax).load('/index.php&i='+imgForAjax);}
doAjax('mom');
It makes the oft-repeated ajax patterns much simpler, and handles the issues between different browsers just as I presume your getXMLhttp function does.
At the website I linked above you can download the library's single 29kb file so you can use it on your pages with a simple <script src='jquery.min.js'></script> There is also a lot of great documentaiton. jQuery is pretty popular and you'll see it has a lot of questions and stuff on SO. ajax is just one of many things that jQuery library/framework (idk the preferred term) can help with.
Hello I have two dependants select box, the second one is popularited after onchange event.
The first one is loaded with a selected value (selected=selected), what I'm asking, it is possible to send the requested while the page is loading, ie as I have the the selected option, just send the request.
Javascript
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getSubCat(catId,incat) {
var strURL="../Includes/subcatAds.php?SubCat="+catId+"&incat="+incat;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('subcat').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
The PHP will be provided if needed
You really need to use jQuery and replace all of the above with:
function getSubCat(catId, incat)
{
$('#subcat').load("../Includes/subcatAds.php?SubCat="+catId+"&incat="+incat);
}
// Run on load:
$( function(){
getSubCat(4, 5);
});
It will do the same thing. It's set up to run on load, and you don't have to worry about cross browser compatibility.
You will find yourself using jQuery selectors all the time and your code will be very lightweight. If you link the jQuery library to Google servers people will not even have to download it. Most people have it in cache already.
You could use the onload event like this:
window.onload = function(){
var selectbox = document.getElementById('select box id');
if (selectbox.value !== ''){
// your code to send ajax requests...
}
};
The code runs as soon as page loads. It then checks if the value of the specified select box is not empty meaning something is selected; in that case you put your code for the ajax request which will execute.
Since you are doing this before getting any input from the user, you could immediately make the call to the server, before the DOM is finished, before the page is fully loaded, and then just wait until the onload event takes place, or you get informed that the DOM tree is finished, and you can then safely change the value of any of the html elements.
This way you don't have the user wait for the browser to finish loading before you even start your request, which will improve the user experience.