I think I'm getting ahead of myself, but I tried AJAX tutorials to read from a PHP file. The PHP file simply has an echo statement for the time, and I want to pass that to initialize a javascript clock.
But this is my first time trying AJAX and I can't even seem to get it to activate a test alert message.
Here is the code, it's at the bottom of my PHP page after all of the PHP.
<script type='text/javascript'>
function CheckForChange(){
//alert("4 and 4");
//if (4 == 1){
//setInterval("alert('Yup, it is 1')", 5000);
//alert('Now it is changed');
//}
var ajaxReady = new XMLHttpRequest();
ajaxReady.onreadystatechange = function(){
if (ajaxReady.readystate == 4){
//Get the data
//document.getElementById('clocktxt').innerHTML = ajaxReady.responseText;
alert("here");
alert(ajaxReady.responseText);
}
}
ajaxReady.open("GET","ServerTime.php",true);
ajaxReady.send(null);
}
setInterval("CheckForChange()", 7000);
</script>
Can somebody tell me why this isn't working? No idea what I'm doing wrong.
The problem in your code is an uncapitalized letter. (Oops!) You check ajaxReady.readystate; you need to check ajaxReady.readyState.
Because ajaxReady.readystate will always be undefined, your alerts never fire.
Here's your code fixed and working.
As an aside, have you considered using a library to handle the ugliness of cross-browser XHR? jQuery is your friend:
function CheckForChange(){
$.get('ServerTime.php', function(data) {
$('#clocktxt').text(data);
});
}
You should probably have something like:
setInterval(CheckForChange, 7000);
On an unrelated note, it's common naming convension in JavaScript to have function and methods names' first letters not capitalized, and the rest is in camelCase. i.e. checkForChange().
I'm not sure the exact problem with your code; here's what I use -- I'm sure it will work for you. (plus, it works with more browsers)
var xhr = false;
function CheckForChange(){
/* Create xhr, which is the making of the object to request an external file */
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
if(window.ActiveXObject){
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
/* End creating xhr */
/* Retrieve external file, and go to a function once its loading state has changed. */
if(xhr){
xhr.onreadystatechange = showContents;
xhr.open("GET", "ServerTime.php", true);
xhr.send(null);
}else{
//XMLHTTPRequest was never created. Can create an alert box if wanted.
}
/* End retrieve external file. */
}
function showContents(){
if(xhr.readyState==4){
if(xhr.status==200){
alert(xhr.responseText);
}else{
//Error. Can create an alert box if wanted.
}
}
}
setInterval(CheckForChange, 7000);
Related
I have a simple jquery function that sends a post request to a PHP file like this:
$.post('/file.php',
{
action: 'send'
},
function(data, textStatus)
{
alert(data);
});
And a PHP file:
<?php
/* Some SQL queries here */
echo 'action done';
/* echo response back to jquery and continue other actions here */
?>
jQuery by default waits till executing the whole PHP script before giving the alert. Is there a way to alert the action done before executing the rest of the PHP file??
Thanks
It is possible with plain Javascript ajax. The onreadystatechange event will fire with a readyState of 3, when data is received before the request is complete.
In the example below, newData will contain the new piece of data. We have to do some processing because the XHR actually gives us the entire data so far in responseText and so if we only want to know the new data, we have to keep a record of the last index.
var httpRequest, lastIndex = 0;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() {
if(httpRequest.readyState === 3) {
var newData = httpRequest.responseText.substring(lastIndex);
lastIndex = httpRequest.responseText.length;
console.log(newData);
}
};
httpRequest.open('POST', '/file.php');
httpRequest.send('action=send');
As for jQuery ajax, this answer suggests jQuery lets you bind to the readystatechange but I haven't tested it.
If I have a list of elements, and via javascript the user moves the elements in another order, can I, after each move, launch a php code (like a php page) but without having to call it in the browser?
Create an XmlHttpObject for the URL, send() it, check results to see if the call was successful, and discard the responseText. As an example, suppose you have the new order in a variable testUrl, e.g., "http://domain.com/script.php?order=1,4,3,2"
var xmlHttpObject = new XMLHttpRequest();
xmlHttpObject.open("GET", testUrl, false);
xmlHttpObject.send();
var xmlText = xmlHttpObject.responseText;
if (xmlText == 'Success')
// do nothing
else
alert (xmlText);
An addition to the above answer - for the sake of posterity, in case someone has to debug your code some day :) I use the following function call to get that object: (I believe it makes the JS more readable and portable). You can check the return value and if null, alert the user that AJAX is not supported by the browser.
function getXmlHttpObject () {
var xmlHttpObject = null;
try {
xmlHttpObject = new XMLHttpRequest();
} catch (ex) {
try {
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
} catch (ex) {
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
return xmlHttpObject;
}
While developing a web app where I'm making great use of javascript php and ajax.
I want to call
display_terminal('feedback_viewer','logs/init-raid-log.txt','Init-Raid');
to build my terminal and call feed_terminal() which has its own setTimeout() recursion call
var url='../edit_initRaid.php';
status_text('Initializing raid-array. Please wait a moment...');
var xmldoc=ajaxPHP2(url,2);
a php file that does nothing more that
exec("sudo /usr/bin/./init-raid-drives-web.sh");
and this is where I fail. This next line is not executed until after the exec() in the php file returns to the php file and the php file returns to the javascript. Not that it matters, but I am pretty sure it did not used to be this way, as originally the bash script would execute over a time period of 2 minutes and the javascript would successfully be updating the html with feed_terminal. this is not the case anymore.
alert("javascript has returned from ajax call");
if (xmldoc) {
status_text('Raid-array initialized successfully. System will now restart.You must re-login to FDAS-Web.');
Below is a bunch of code for your questions
Ultimately my question is, how can I run javascript DURING the ajax call?
Or maybe my question should be, how can I have edit_initRaid return an xmldoc, without waiting for the exec() to return, or how can i have the exec() return even without the script completing?
function initRaidArray(){
if (document.getElementById('initRaid_doubleCheck')){
if (document.getElementById('initRaidHideButtonSpot'))
document.getElementById('initRaidHideButtonSpot').innerHTML = '';
var spot=document.getElementById('initRaid_doubleCheck');
spot.innerHTML='';
spot.innerHTML='This may take a few moments. Please wait.';
}
display_terminal('feedback_viewer','logs/init-raid-log.txt','Init-Raid');
var url='../edit_initRaid.php';
status_text('Initializing raid-array. Please wait a moment...');
var xmldoc=ajaxPHP2(url,2);
alert("javascript has returned from ajax call");
if (xmldoc) {
status_text('Raid-array initialized successfully. System will now restart. You must re-login to FDAS-Web.');
}
}
where display_terminal() does two things, builds a table and appends it to the page, and calls feed_terminal(logfile,bigDiv,0)
function feed_terminal(logFile,bigD,lap){
// AJAX
bigD.innerHTML = '';
var url='../view_xml_text.php';
/*
* lap(0)=clear file , lap(1)=do not clear file
*/
url+='?logFile='+logFile+'&lap='+lap;
var XMLdoc=ajaxPHP2(url,2);
var xmlrows = XMLdoc.getElementsByTagName("line");
alert("xmlrows.length=="+xmlrows.length);
// empty file
if (xmlrows.length==0){
var d = document.createElement('div');
var s = document.createElement('span');
s.innerHTML='...';
d.appendChild(s);
bigD.appendChild(d);
} else {
// Parse XML
for (var i=0;i<xmlrows.length;i++){
if (xmlrows[i].childNodes[0]){
if (xmlrows[i].childNodes[0].nodeValue){
var d = document.createElement('div');
var s = document.createElement('span');
s.innerHTML=xmlrows[i].childNodes[0].nodeValue;
d.appendChild(s);
bigD.appendChild(d);
}
}
}
}
setTimeout(function(){feed_terminal(logFile,bigD,1)},2000);
}
where the most important item is the setTimeout() call to continue reaching out to the php file which returns xml of the lines in the file, simply.
function ajaxPHP2(url,key)
{
if (window.XMLHttpRequest) {
xml_HTTP=new XMLHttpRequest();
if (xml_HTTP.overrideMimeType) {xml_HTTP.overrideMimeType('text/xml');}
} else { xml_HTTP=new ActiveXObject("Microsoft.xml_HTTP"); }
xml_HTTP.open("GET",url,false);
xml_HTTP.send(null);
if (key){return xml_HTTP.responseXML;}
}
You need to tell Javascript to do your XHR call asynchronously.
Change
xml_HTTP.open("GET",url,false);
to
xml_HTTP.open("GET",url,true);
But first, you'll need to tell it to do something when the request completes (a callback):
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
One recommendation: XHR is a pain. It would be a lot easier to use something like jQuery's $.ajax()
You need to set your ajax call to be asynchronous. In the ajaxPHP2 function, the line xml_HTTP.open("GET", url, false); is what is causing the page to pause. The false parameter is telling the ajax call to make everything else wait for it. Change the false to true so it looks like this:
xml_HTTP.open("GET", url, true);
You may also need to attach a function to the onreadystatechange property so that when the ajax call returns it knows what to do. See these links for more information.
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.
I'm new to AJAX, and trying to use it to speed up the display of results for a PHP full-text file search. I have about 1700 files to search, so instead of waiting for the server to process everything I want to send just the first 100 to the script and display the results, then the next 100 etc., so users get instant gratification.
To do this, I call a function callftsearch with the names of all the files in a string and some other information needed for the PHP function on the other side to run the search. callftsearch creates arrays of each 100 files, joins them in strings and sends that to ftsearch.php through the javascript function ftsearch. The PHP runs the search and formats the results for display, and sends the HTML string with the table back. addresults() just appends that table onto an existing div on the page.
Here's the javascript:
function GetXmlHttpObject()
{
var xmlHttp=null;
try { xmlHttp=new XMLHttpRequest(); }
catch (e) { try { xmlHttp=new ActiveXObject('Msxml2.XMLHTTP'); }
catch (e) { xmlHttp=new ActiveXObject('Microsoft.XMLHTTP'); } }
return xmlHttp;
}
function callftsearch(allfiles, count, phpfilenames, keywordscore, keywordsboolean, ascii) {
var split_files = allfiles.split("|");
var current_files = new Array();
var i;
for (i = 1; i<=count; i++) {
file = split_files.shift();
current_files.push(file);
if (i%100 == 0 || i == count) {
file_batch = current_files.join('|');
ftsearch(file_batch, phpfilenames, keywordscore, keywordsboolean, ascii);
current_files.length = 0;
}
}
}
function ftsearch(file_batch, phpfilenames, keywordscore, keywordsboolean, ascii)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) { return; }
// If our 'socket' has changed, send the response to addresults()
xmlHttp.onreadystatechange=addresults;
xmlHttp.open('POST','ftsearch.php', true);
var content_type = 'application/x-www-form-urlencoded';
xmlHttp.setRequestHeader('Content-Type', content_type);
xmlHttp.send('f='+file_batch+'&pfn='+phpfilenames+'&kw='+keywordscore+'&kwb='+keywordsboolean+'&a='+ascii);
}
function addresults()
{
var displayarray = new Array();
if (xmlHttp.readyState==4)
{
var ftsearchresults = xmlHttp.responseText;
$('#result_tables').append(ftsearchresults);
}
}
The problem: the page displays the exact same table repeatedly, with only the first few results. When I add alert(file_batch) to callftsearch it shows that it's sending the correct packets of files in succession. But when I alert(ftsearchresults) in addresults() it shows that it's receiving the same string over and over. I even added a timestamp at one point and it was the same for all of the printed tables.
Why would this happen?
A few things here.
First: it looks like you are already using jQuery since you have the line,
$('#result_tables')
If thsts the case, then why not use jQuerys built in ajax functionality? You could just do something like this,
$.ajax({
type: "POST",
url: "ftsearch.php",
data: 'f='+file_batch+'&pfn='+phpfilenames+'&kw='+keywordscore+'&kwb='+keywordsboolean+'&a='+ascii,
success: function(response){
$('#result_tables').append(response);
}
});
Second: If the output continues to be the same first few items each time, have you tried outputting the information that the ajax page is receiving? If it is receiving the correct information, then that meens there is something wrong with your PHP logic, which you do not have posted.