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
Related
I'm using an AJAX function to grab some data from a database and run a simple if statement. I want to use the output variable "test" to change the class (and therefore styling) of an SVG group. I was originally using PHP on page load but now that I'm using AJAX I have to use JavaScript and it isn't working.
Here's the AJAX:
function loadfacebook1()
{
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)
{
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("fbname").innerHTML=obj.name;
document.getElementById("fbtraffic").innerHTML=obj.traffic;
document.getElementById("fbrevenue").innerHTML=obj.revenue;
document.getElementById("fbprofit").innerHTML=obj.profit;
document.getElementById("fbrafrica").innerHTML=obj.rafrica;
var test = document.getElementById('fbrafrica').value;
if(test > 100)
{var africastyle = "b1";
}
}
}
xmlhttp.open("GET","getfacebook.php",true);
xmlhttp.send();
}
And here is the group that I'm trying to change the class of:
<g class="<?php echo $africastyle ;?>" transform="translate(0,239) scale(0.016963,-0.016963)">
As you can see it uses PHP at the moment but how to I replace this with the JavaScript variable "test" that I assigned in the AJAX function?
Thanks,
Will
Here's what I would do. Add an ID to your group element.
HTML:
<g id="myGroup">
JS:
if(test > 100){
var el = document.getElementById('myGroup');
el.setAttribute('class', 'b1');
}
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¶m2=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>
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.
New to JSON/AJAX here but trying...
PHP page appears to be returning [{"id":"1"},{"id":2}] to my javascript.
How would I convert it to something useful like a dropdown in html?
Code:
<script>
function show(str) {
if (str=="") {
var ajaxDisplay=xmlhttp.responseText;
var res=ajaxDisplay.split("#");
document.getElementById("ajax1").innerHTML=res[1];
return;
}
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) {
var ajaxDisplay=xmlhttp.responseText;
var res=ajaxDisplay.split("#");
document.getElementById("ajax1").innerHTML=res[0];
}
}
xmlhttp.open("GET","get.php?q="+str,true);
xmlhttp.send();
}
</script>
<div id='ajax1'><b>ID dropdown will be listed here.</b></div>
I am not sure why you declared the variables twice, but I think this may help If you are asking what I think.
function showUser(fo,to)
{
if (fo=="")
{
document.getElementById("show").innerHTML="";
return;
}
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)
{
var arr=xmlhttp.responseText.split(":||:");//I used this as the delimiter
document.getElementById('show').innerHTML=arr[0];
document.getElementById('show1').innerHTML=arr[1];
}
}
xmlhttp.open("GET","some.php?q="+ fo + "&w=" + to,true);
xmlhttp.send();
}
And the php side is different than normal, you;ll need something like this.
if (!$result=mysqli_query($con,$sql))
{
die('Could not get data: ' . mysqli_error($sql));
}
$test=mysqli_fetch_all($result,MYSQLI_ASSOC);//this was key to fetching the array properly for display
$length=count($test);
$half_length=$length/2;
//echo $half_length."<br />";/used for testing
$test12=array_chunk( $test,$half_length+.5,false);//here use true to preserve keys, worked both ways for me
$test5=$test12[0];
$test6=$test12[1];
while(list($key,$val)=each($test5))
{
echo "<p>".$val[$colunm_name]."<p/><br />";//Here you can put in the tags you want and will list your array in the format you want
}
echo ":||:";//Make sure the delimiter is out of the loop
while(list($key2,$val2)=each($test6) )
{
echo "<p>".$val[$colunm_name]."<p/><br />";//Here you can put in the tags you want
//echo "result_count_".count($test)."_-st<br/>";//used for testing
Took me a while to get this, I hope it helps.
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);