Run php script every x mins using ajax request - javascript

got this file 'functions.php':
<?php
function test ($url){
$starttime = microtime(true);
$valid = #fsockopen($url, 80, $errno, $errstr, 30);
$stoptime = microtime(true);
echo (round(($stoptime-$starttime)*1000)).' ms.';
if (!$valid) {
echo "Status - Failure";
} else {
echo "Status - Success";
}
}
test('google.com');
?>
I want to run it every 10seconds or so, i was told to use ajax request but i dont completely understand how it works. I tried creating a new file 'index.php', and then had this written in it:
<script>
var milliSeconds = 10000;
setInterval( function() {
//Ajax request, i dont know how to write it
xmlhttp.open("POST","functions.php",true);
xmlhttp.send();
}, milliSeconds);
</script>
I put both files into ftp but nothing happens, can someone help me write a propper ajax request?
Edit: eddited typo, still doesnt work tho

var milliSeconds = 1000;
setInterval( function() {
var xmlhttp;
if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log ( xmlhttp.responseText );
}
}
xmlhttp.open("POST","functions.php",true);
xmlhttp.send();
}, milliSeconds);
You have to load xmlhttp request object according to the browser ( xmlhttp=new XMLHttpRequest(); ), then set an event handler when the xmlhttp state changes ( xmlhttp.onreadystatechange=function() ). When it changes check if the status is 200 (success) then do whatever you want with the response. ( I printed it to console )

So, it sounds like your only problem is that you don't know how to write an XHR request. Take a look at Using XMLHttpRequest. Comment on this answer with your questions.

xmlhttp.open("POST","funkction.php",true);
should be:
xmlhttp.open("POST","functions.php",true);

Related

javascript countdown and updates database php

I would like to implement a JavaScript code to count down hundred seconds. I have written the code for count down, but I need the value of the remaining time and update it in a database on every second. Below is an example of what I would like to accomplish:
On Every second I would like to run:
UPDATE 'table' SET 'timeleft=[remaining time]'
Is this possible?
Below is what I've tried so far:
<? $time = "100"; ?>
<script>
var intCountDown = <?php echo $time; ?>;
function countDown()
{
if(intCountDown < 0)
{
cntdwn.innerText = 'Done';
return;
}
cntdwn.innerText = intCountDown--;
setTimeout("countDown()",1000);
}
</script>
Then just: <div id=cntdwn></div>
Additionally this may help clarify my intention: I want to implement a single-shot timer but prefer the counter to overflow back to where it started after the page refresh.
To do that, you'll need AJAX:
here is your AJAX function:
function loadXMLDoc(timeleft)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
cntdwn.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","update.php?timeleft="+timeleft,true);
xmlhttp.send();
}
Using above function, we can send an int to update.php?timeleft= and update.php should connect to database and update your timeleft value (i think you wrote it anyway). and in your countdown function just replace this line:
cntdwn.innerText = intCountDown--;
with this(since we will update innerText in ajax call):
intCountDown--;
that's all needs to be done

AJAX won't get PHP - echo

So I'm trying to build a pretty simple website, to learn basic webdesign. It's just a random quote generator - you click on a button and it prints some famous quote. Anyway, I try to use ajax to get the quote, so I use this function:
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","RandomQuote.php",true)
xmlhttp.send();
}
but no matter what I type into RandomQuote.php, even if it's something like :
<?php
echo 'Hello, world';
?>
nothing shows up in the quote "div', it just becomes blank. I really have no idea what's the problem here. Thanks for the help!
Well, I'm not sure about much, but are you calling your function? You put your ajax inside loadXMLDoc() , so you probably have to call it. Another way is to put your ajax into an addEventListener so when a user clicks on something, it'll execute. If that's not the problem, try making sure your element in your html page with the id of "quote" is spelled correctly. Sometimes the latter scenario is always the problem for me.
$.get( "RandomQuote.php", function( data ) {
$( "#quote" ).html( data );
console.log( "Load was performed." );
});
Don't forget to include jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
This is my ajax function, try to use it:
/**
* #function ajax Send ajax-request with post
* #param {string} xmlpage Target url
* #param {string} data Post parameters (like param1=val1&param2=val2...)
* #param {Function} callback
* #return {null}
*/
function ajax(xmlpage, data, callback)
{
var xmlh = null;
if(window.XMLHttpRequest)
xmlh = new XMLHttpRequest();
else
try
{
xmlh = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(ex)
{
xmlh = new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlh)
{
xmlh.open("post", xmlpage, true);
xmlh.onreadystatechange = function(x)
{
if(xmlh.readyState==4 && typeof callback !== 'undefined')
callback(xmlh.responseText);
}
xmlh.setRequestHeader("Accept-Language","ru, en");
xmlh.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlh.send(data);
}
}
Following test files using your code from the question. It is working perfectly. Either you are missing something or its a browser issue. I tested on Mozilla. To be sure of browser independent code use jQuery for Ajax call
test.html
<html>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","RandomQuote.php",true)
xmlhttp.send();
}
</script>
<div id="quote"></div>
<input type="button" value="Click Me" onclick="loadXMLDoc()"/>
</html>
RandomQuote.php
<?php
echo 'hi';
Update: jQuery version
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function loadXMLDoc()
{
$.get( "RandomQuote.php", function( data ) {
$( "#quote" ).html( data );
});
}
</script>
<div id="quote"></div>
<input type="button" value="Click Me" onclick="loadXMLDoc()"/>
</html>

AJAX variable are not reading from PHP file?

This is my javascript that holds the function to save the file.
function saveMap()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
map = document.getElementById("sectorTableMap").innerHTML;
data = '<table id="sectorTableMap">';
data += map;
data += '</table>';
document.getElementById("sectorTableMap").innerHTML = data;
//alert("done");
//alert(data);
if(fileName=="lastSave - RENAME") {
return alert("Please set a file name under [CONFIG]");
}
else {
//alert(data);
//alert(user);
//alert(fileName);
xmlhttp.open("POST","http://pardustools.comuf.com/saveMap.php?t="+Math.random(),true);
xmlhttp.send('map='+data+'&user='+user+'&fileName='+fileName);
//alert(data);
//alert(user);
//alert(fileName);
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//return alert("File has successfully been saved!");
return alert(xmlhttp.responseText);
}
}
}
This is my files that is posted too.
<?php
$user = strtolower($_POST['user']);
$map = $_POST['map'];
$fileName = "savedMaps/".$user."/".$_POST['fileName'].".html";
file_put_contents($fileName,$map);
echo $fileName."<br />".$map;
?>
This is the output I receive on the php file.
savedMaps//.html
It should be more like this
savedMaps/randomName/fileName.html
EDIT:
To set for the user.
user = "<?php $cookie = $_COOKIE['mapperlogauth']; echo strtolower($cookie['user']);?>";
To set for the data...
It is under the saveMap() function and starts with map.
You are using PHP's $_POST get, you're not posting any variables, you should use $_GET in your situation, or change your xmlhttp send to post properly. edit you are also missing the content type header to do a successful post
edit You should also be aware that there is a limit on how much you can send through using the technique you're using. (which is a get, not a post, even though you specify it)
I'd also recommend looking into jQuery for cross-browser compatibility and ease of use.
edit
Here's some code that will allow you to pick it up via POST:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
Have you tried to use :
xmlhttp.send('map=dummy&user='+user+'&fileName='+fileName);
I doubt it may be caused by the encoding.

Ajax resending XMLHttpRequest

I've got a client side js/ajax script like this:
<p>server time is: <strong id="stime">Please wait...</strong></p>
<script>
function updateAjax() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==3 && xmlhttp.status==200) {
document.getElementById("stime").innerHTML=
xmlhttp.responseText;
}
if (xmlhttp.readyState==4) {
xmlhttp.open("GET","date-sleep.php",true);
xmlhttp.send();
}
}
xmlhttp.open("GET","date-sleep.php",true);
xmlhttp.send();
}
window.setTimeout("updateAjax();",100);
</script>
And a on the server side:
<?php
echo 6;
for ($i=0; $i<10; $i++) {
echo $i;
ob_flush(); flush();
sleep(1);
}
?>
After first 'open' and 'send' it works ok, but when the server finishes the script and xmlhttp.readyState == 4 then the xmlhttp resends the request but nothing happens.
Instead of re-using the same XHR object all the time, try repeating the function with a new object. This should at least fix incompatibility issues as you listed.
Try re-calling your Ajax function inside the callback of it, if you want to loop it infinitely.
if (xmlhttp.readyState==4) {
updateAjax(); //or setTimeout("updateAjax();",100); if you want a delay
}
I'd also suggest putting your .innerHTML method inside the .readyState==4, which is when the requested document has completely loaded, and .status==200 which means success. Like this:
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("stime").innerHTML=
xmlhttp.responseText;
updateAjax(); //or setTimeout("updateAjax();",100);
}
Also, if you want your Ajax to be cross-browser, you should test if the browser supports the XHR object which you're using:
var xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
I just typed the code above but it should work just fine to add compatibility with older versions of IE and other browsers.

more than one ajax call in the same page?

I have the following code
function ajaxCall(action,parameters){
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//xmlhttp.overrideMimeType('text/html');
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var rtrv_data=xmlhttp.responseText;
alert(rtrv_data);
}
}
parameters='action=' + action + '&' + parameters;
xmlhttp.open("POST","ajax_calls.php" ,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);
}
Assuming that i have this function called by some timer , and a click on the page called the function again , i only get one output ! one response ! hwo can i get the 2 ?
thanky you .
The variable "xmlhttp" is a global (you used no "var") so this will never allow two simultaneous ajax calls because when the second call starts you will overwrite the same variable and that's the variable that's used inside the callback to retrieve the data.
You need to create a new variable each time to store the xml request object and also you need to use a closure for your completion callback... something like
var xmltthp = ... // this is a local variable
xmlhttp.onReadyStateChange = function() {
// here you can use xmlhttp even if it's a local
// it will be a different variable for each ajax request
}
Thanks! That worked for me! Did this:
function refreshpage(){
var mycode=document.getElementById("bcode").value;
if (window.XMLHttpRequest){
xmlhttpf=new XMLHttpRequest();
}else{
xmlhttpf=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpf.onreadystatechange=function(){
if (xmlhttpf.readyState==4 && xmlhttpf.status==200){
document.getElementById("zones").innerHTML=xmlhttpf.responseText;
}
}
xmlhttpf.open("GET","ajaxaki.php?code="+mycode,true);
xmlhttpf.send();
}
function refresh_vehs(){
var asma=document.getElementById("newasma").value;
if (window.XMLHttpRequest){
xmlhttpf_vehs=new XMLHttpRequest();
}else{
xmlhttpf_vehs=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpf_vehs.onreadystatechange=function(){
if (xmlhttpf_vehs.readyState==4 && xmlhttpf_vehs.status==200){
document.getElementById("vehicles").innerHTML=xmlhttpf_vehs.responseText;
}
}
xmlhttpf_vehs.open("GET","AJAX_vehicle_cards.php?asma="+asma,true);
xmlhttpf_vehs.send();
}

Categories