AJAX and auto-refreshing - php

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);

Related

SimpleXMLElement slow performance

I am using SimpleXMLElement() to obtain data from a website, which is used to embed data. The code I am using is as follows:
$rss = new SimpleXMLElement('http://eliteprospects.com/rss_player_stats2.php?player='.$player_array[0]['embed_stats'], null, true);
foreach($rss->xpath('channel/item') as $item)
{
echo utf8_decode($item->description);
}
This works great, except for one issue, the data loads exceptionally slow from the other site. The page load goes from approximately 0.5-1s to 2.5-3s.
Is there a method that I can use, to load the asynchronously, or is there a faster function I should be using instead?
An idea that came to mind was to load a separate page within an iFrame after the initial page load, or is there a better method?
Is there a method that I can use, to load the asynchronously, or is
there a faster function I should be using instead?
Unfortunately, there is nothing to do about the long response time (trivially assuming that connection speed in not archaic). Also echoing out the results all at once might slow down the browser rendering and thus the page load time.
AJAX fits nicely here - wait for window.onload and trigger the AJAX call to your webservice (holds the snippet from question) to prepare the output buffer and return the response to browser. Afterwards set/replace the innerHTML value of selected DOM element with the response.responseText.
Pseudo-code
window.onload = function()
{
var url = 'http://example.com/webserice';
Ajax.get(url, function(response)
{
var responseText = response.responseText;
document.getElementById('someid').innerHTML = responseText;
}
}
The snippet I am using in pure JS, although jQuery has a lot more appealing way to do it
Ajax = {
request : {},
createRequest : function()
{
var request = false;
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest();
}
else
{
if (window.ActiveXObject)
{
request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
else
{
request = false;
}
}
return request;
},
get : function(page, callback)
{
var self = this;
var request = this.createRequest();
if (! page)
{
return false;
}
request.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
delete self.request;
if (typeof callback == 'function')
{
callback(request);
}
else
{
self.update(request, callback);
}
var regex = /<script\b.*?>([\s\S]*?)<\/scri/ig;
var match;
while (match = regex.exec(request.responseText))
{
eval(match[1]);
}
}
}
request.open('GET', page, true);
request.setRequestHeader('X-Requested-With', 'ajax');
request.send(null);
}
}

How do I get ajax to intermittently call my php?

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

Refreshing my php page with AJAX every 5 seconds

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.

jquery image slider with ajax

I'm loading external php pages through ajax. The external pages consists of jquery based image slider. It doesn't get loaded. Here I call the page through Ajax.
Load Jquery
it gets loaded but the navigating functions within that page doesn't work.
here is the ajax navigation which is called
var please_wait = null;
function open_url(url, target) {
if (!document.getElementById) {
return false;
}
if (please_wait != null) {
document.getElementById("target").innerHTML = please_wait;
}
if (window.ActiveXObject) {
link = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
link = new XMLHttpRequest();
}
if (link == undefined) {
return false;
}
link.onreadystatechange = function() {
response(url, target);
}
link.open("GET", url, true);
link.send(null);
}
function response(url, target) {
if (link.readyState == 4) {
document.getElementById(target).innerHTML = (link.status == 200) ? link.responseText : "Ooops!! A broken link! Please contact the webmaster of this website ASAP and give him the fallowing errorcode: " + link.status;
}
}
function set_loading_message(msg) {
please_wait = '<img src="images/ajax-loader.gif"/>';
}
Where do I make the correction to make it work with my Jquery based page.

javascript send one way message to php

How can I use javascript to send a one way message to php? I would like to get the browser information from javascript and just send it to php in the background. I know I can get some of this from php, but I'd rather use javascript. Is there a way to do this without a framework like jquery?
Yes, you can do it with something like this:
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
alert('Here goes something');
self.xmlHttpReq.send('browser info here');
}
}
}
This will send "browser info here" as POST in the php page you pass to the function as url. I didnt test it though
You would have to submit an AJAX request to a PHP script. Yes, you could do it without using a framework but I wouldn't advise it.
You need to make an AJAX call to a PHP page, preferably using POST. Any data you want to send needs to be sent along with the request.
I recommend using a framework such as jQuery, but if you insist on using raw JavaScript, you want to research XMLHttpRequest.
// fix for older IE versions
// see http://blogs.msdn.com/b/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
if( typeof window.XMLHttpRequest === 'undefined' &&
typeof window.ActiveXObject === 'function') {
window.XMLHttpRequest = function() {
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
return new ActiveXObject('Microsoft.XMLHTTP');
};
}
function postData(url, data, errhandler) {
var req = new XMLHttpRequest;
req.onreadystatechange = function() {
if(this.readyState === 4 && this.status !== 200 && errhandler)
errhandler(this);
};
try {
req.open('POST', url, true); // async post request
req.send(data);
}
catch(e) {
if(errhandler)
errhandler(req);
}
}

Categories