I just have a json page in localhost and I save the data of this page in a file , I need to save this page every 5 seconds, so I developed this code in ajax , using a page in php with an exec command,I used a setinterval function for the update but my code execute the function getRequest only one time.
Here the html:
<script type="text/javascript">
// handles the click event for link 1, sends the query
function getOutput() {
setInterval(function(){
getRequest(
'prova1.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
},3000);
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
</script>
And here the php page:
<?php
exec(" wget http://127.0.0.1:8082/Canvases/Fe0_Cbc1_Calibration/root.json -O provami3.json", $output);
echo 'ok';
?>
I'm new to php , javascript ajax etc and I-m learning it a piece at time, I know that maybe there is an easy way for it using jQuery but for now I'm learning Ajax, so I'd like have an advice for doing it with Ajax.
Thank you all.
Do you have called getOutput() function?I don't see it...
Working example with your code here: http://jsfiddle.net/v9xf1jsw/2/
I've only added this at the end:
getOutput();
Edit:
Working example with getOutput call into a link: http://jsfiddle.net/v9xf1jsw/8/
The JS is fine, see example here counting the loops https://jsfiddle.net/tk9kfdna/1/
<div id="output"></div>
<div id="log"></div>
<script type="text/javascript">
// handles the click event for link 1, sends the query
var times=0;
function getOutput() {
setInterval(function(){
getRequest(
'prova1.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
},3000);
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
function getRequest(url, success, error) {
times++;
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
var log = document.getElementById('log');
log.innerHTML = 'Loop:'+times;
return req;
}
getOutput();
</script>
Assuming here your calling getOutput() somewhere as that was not included in your original question if not it may just be that. Otherwise what may be happening is a response from prova1.php is never being received and so the script appears like it's not working. The default timeout for XMLHttpRequest request is 0 meaning it will run forever unless you specify the timeout.
Try setting a shorter timeout by adding
req.timeout = 2000; // two seconds
Likely there is an issue with prova1.php? does prova1.php run ok when your try it standalone.
1) Return false at the end of the setInterval method, I don't believe this is necessary.
2) Use a global variable to store the setInterval, (this will also give you the option to cancel the setInterval).
var myInterval;
function getOutput() {
myInterval = setInterval(function(){
getRequest(
'prova1.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
},3000);
}
Related
So I want to use buttons on my HTML page to call a php program that will write to a text file. What I currently get is a success package from my Ajax function, but the file that it has supposed to have written does not exist.
my HTML
<button type = "button" onclick = "getRequest('changeState.php', changeState('1'), 0)"></button>
my Javascript functions:
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
}
catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function()
{
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
function changeState(input)
{
state = input;
document.GetElementById("state_current").innerHTML = state;
}
My PHP file:
<?php
$f = fopen("file.txt");
fwrite($f, "Hello World");
fclose($f);
?>
I'll be honest, I'm very new to php, but my syntax seems fine because I'm not dropping any error messages, and I know that the program runs successfully because I get the success function to run. Have I missed something glaringly obvious?
file.txt should be created, if calling your PHP-script directly. If not probably PHP is not allowed to create it. Unfortunately its not that easy to understand which user is used to run PHP, and this user must have the rights to write to the webroot-folder of the server. As far as I know this depends on how PHP is executed (module vs CGI).
I would give it a try to change the folders access rights to "777" (anyone is allowed to do anything).
The changeState function doesn't get called on success because you are passing the value returned by the changeState function not the function reference, should be:
<button type = "button" onclick = "getRequest('changeState.php', changeState, 0)"></button>
You can also check on the Network Tab on the Developers Tools to see if you actually sent the request to the URL. If you didn't, then there's something wrong with your URL or your server.
Here is the getapps function which loads application names from my website.
getapps = function (applist){
var xmlhttp = new XMLHttpRequest();
var url = "http://mywebsite.com/"+applist;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(data) {
var i;
var query = data.data;
if(query != ''){
for(i = 0; i < query.length; i++) {
var appinstall='';
appAvailability.check(
query[i].appid, // URI Scheme or Package Name
function() { // Success callback
appinstall = "is available :)";
console.log(query[i].appid+"is available :)");
},
function() { // Error callback
appinstall = "is not available :(";
console.log(query[i].appid+"is not available :(");
}
);
console.log(appinstall);
}
}
}
}
console.log which is outside appAvailability.check function fires first for n times Within next few seconds console.log which is inside appAvailability.checkfunction fires up for n times with error undefined appid.
I Tested by removing for loop and predefining appid which worked really well without errors.
How can i resolve this by making the loop wait until appAvailability.check is completed ?
It's because appAvailability.check executes a success and a failure callback.
I strongly suspect your code is making a native call in that callback which is running the callback after your callback has executed.
You can get around this using recursion as follows:
function getApps(appslist) {
var xmlhttp = new XMLHttpRequest(),
url = "http://mywebsite.com/"+applist;
callback = callback || function() {};
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
if (data != ''){
checkApp(data.data);
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function checkApp(applist, callback) {
var app = applist.push();
if (!app) {
callback();
return;
}
appAvailability.check(
app.appid, // URI Scheme or Package Name
function() { // Success callback
console.log(app.appid + "is available");
// handle availability here
checkApp(applist, callback);
},
function() { // Error callback
console.log(app.appid + "is not available");
// handle absence here
checkApp(applist, callback);
}
);
}
This is the code I wrote:
function responseAjax(element, url, loader, data) {
if(request.readyState == 4) {
if(request.status == 200) {
//The response has 2 main parts: the main page element and the javascript that have the text "???PHPTOSCRIPT???" in between
output = request.responseText.split('???PHPTOSCRIPT???');
if (element) document.getElementById(element).innerHTML = output[0];//put first part into element
if (output[1] != "") eval(output[1]); //execute script
//remember the last request
if (typeof(url) !== 'undefined') {
document.cookie = "requestedURL=" + escape(url);
document.cookie = "requestedElement=" + escape(element);
document.cookie = "requestedLoader=" + escape(loader);
document.cookie = "requestedData=" + escape(data);
};
};
};
};
function ajax(url, element, loader, data, remember, async) {
remember = (typeof(remember) === 'undefined') ? false : remember;//remember last request. Default: false
async = (typeof(async) === 'undefined') ? true : async;//handle request asynchronously if true. Default: true
if (loader) document.getElementById(element).innerHTML = loader;
try { request = new XMLHttpRequest(); /* e.g. Firefox */}
catch(err) {
try { request = new ActiveXObject("Msxml2.XMLHTTP"); /* some versions IE */}
catch(err) {
try { request = new ActiveXObject("Microsoft.XMLHTTP"); /* some versions IE */}
catch(err) { request = false;}
}
}
if (request) {
url += "?r=" + parseInt(Math.random()*999999999);//handle the cache problem
//put an array of data into string. Default: null array
data = data || [];
for (var i = 0; i < data.length; i++) {
url += "&" + data[i];
};
request.open("GET", encodeURI(url), async);
url = url.split('?');//get query string for remembered request
request.onreadystatechange = (remember) ? function() {responseAjax(element, url[0], loader, data.join('&'));}
: function() {responseAjax(element)};
request.send(null);
} else {
document.getElementById(element).innerHTML = "<h3>Browser Error</h3>";
};
};
Though I use eval() to handle returned script, the script doesn't work on events after all if I use pure javascript. However, if I use jQuery such as $("#tab-panel").createTabs();, this code works fine.
Can someone please explain why pure javascript on the loaded content of ajax doesn't work?
Additional information: As I said, pure javascipt such as function sent through the ajax content doesn't work on events, however another code such as alert() works fine.
When trying to get the responseText from an ajax call built in plain vanilla javascript, Firebug seems to see the request but one cannot get a reference to the responseText.
This is the code for function
function getAjaxResponse(){
var ajaxObj = getAjaxObj();
ajaxObj.open('get', 'responsePage.php', true);
ajaxObj.onReadyStateChanged = function(){
if(ajaxObj.readyState == 4
&& ajaxObj.status == 200){
//no functions are getting fired in here
//this does not get logged to console
console.log(ajaxObj.responseText);
//neither does this
console.log(2);
}
};
ajaxObj.send(null);
//this does gets logged to console
console.log(1);
}
function for the ajax object
function getAjaxObj(){
var req;
if(window.XMLHttpRequest){
try{
req = new XMLHttpRequest();
} catch(e){
req = false;
} finally {
return req;
}
} else {
if(window.ActiveXObject){
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e){
try{
req = new ActiveXObject("Msxml.XMLHTTP");
} catch(e){
req = false;
} finally {
return req;
}
}
}
}
}
Also here is the view from firebug
How to get a reference to the response from the ajax call?
OnReadyStateChanged needs to be onreadystatechange. JavaScript is case-sensitive.
ajaxObj.onReadyStateChanged: onreadystatechange should all be lower case (and without the trailing 'd')
I'm looking to setup a web page that samples data via AJAX calls from an embedded web-server. How would I set up the code so that one request doesn't overlap another?
I should mention I have very little JavaScript experience and also a compelling reason not to use external libraries of any size bigger than maybe 10 or so kilobytes.
You may want to consider the option of relaunching your AJAX request ONLY after a successful response from the previous AJAX call.
function autoUpdate()
{
var ajaxConnection = new Ext.data.Connection();
ajaxConnection.request(
{
method: 'GET',
url: '/web-service/',
success: function(response)
{
// Add your logic here for a successful AJAX response.
// ...
// ...
// Relaunch the autoUpdate() function in 5 seconds.
setTimeout(autoUpdate, 5000);
}
}
}
This example uses ExtJS, but you could very easily use just XMLHttpRequest.
NOTE: If you must have an exact interval of x seconds, you would have to keep track of the time passed from when the AJAX request was launched up to the setTimeout() call, and then subtract this timespan from the delay. Otherwise, the interval time in the above example will vary with the network latency and with the time to processes the web service logic.
I suggest you use a small toolkit like jx.js (source). You can find it here: http://www.openjs.com/scripts/jx/ (less than 1k minified)
To setup a request:
jx.load('somepage.php', function(data){
alert(data); // Do what you want with the 'data' variable.
});
To set it up on an interval you can use setInterval and a variable to store whether or not a request is currently occuring - if it is, we simple do nothing:
var activeRequest = false;
setInterval(function(){
if (!activeRequest) {
// Only runs if no request is currently occuring:
jx.load('somepage.php', function(data){
activeRequest = false;
alert(data); // Do what you want with the 'data' variable.
});
}
activeRequest = true;
}, 5000); // Every five seconds
AJAX, despite the name, need not be asynchronous.
Here is the asynchronous method...
var req;
function ajax(method,url,payload,action)
{
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
req.onreadystatechange = action;
req.open(method, url, true);
req.send(payload);
}
else if (window.ActiveXObject)
{
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = action;
req.open(method, url, true);
req.send(payload);
}
else
{
alert("Could not create ActiveXObject(Microsoft.XMLHTTP)");
}
}
}
...but here is a synchronous equivalent...
function sjax(method,url,payload,action)
{
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
req.open(method, url, false);
req.send(payload);
action();
}
else if (window.ActiveXObject)
{
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = action;
req.open(method, url, false);
req.send(payload);
}
else
{
alert("Could not create ActiveXObject(Microsoft.XMLHTTP)");
}
}
}
... and here is a typical action ...
function insertHtml(target)
{
var pageTarget = arguments[0];
if (req.readyState == 4) // 4 == "loaded"
{
if (req.status == 200) // 200 == "Ok"
{
if (req.responseText.indexOf("error") >= 0)
{
alert("Please report the following error...");
pretty = req.responseText.substring(req.responseText.indexOf("error"),1200);
pretty = pretty.substring(0,pretty.indexOf("\""));
alert(pretty + "\n\n" + req.responseText.substring(0,1200));
}
else
{
div = document.getElementById(pageTarget);
div.innerHTML = req.responseText;
dimOff();
}
}
else
{
alert("Could not retreive URL:\n" + req.statusText);
}
}
}