I have this html and ajax file, but it is not updating every second like I want it to. I want it to every second call getTime(). It only does it once, then nothing.
Any thoughts? Thanks.
<head>
<title>Auction</title>
<script type="text/javascript">
function getTime() {
if (str=="") {
document.getElementById("txtHint").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) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","functions.php?action=getCurrentTime&id=13",true);
xmlhttp.send();
setTimeout(getTime, 1000);
}
window.setInterval(getTime, 1000);
</script>
</head>
<body>
<?php beginGetAllInfo(); ?>
</body>
Based on your sample code, the first thing that happens inside getTime() is it checks if a variable named str is empty, if so, it returns from the function. str isn't defined (in your sample code), so it should return. Try removing that if-statement, or initialize str to something that won't cause the statement to fail.
Additionally, you have two statements that will (eventually) cause your code to execute twice per second:
setTimeout(getTime, 1000);
and
window.setInterval(getTime, 1000);
The first, setTimeout() will execute the code one-time, after 1-second has elapsed. However, this is executed everytime the getTime() method executes - so in theory it should run every second.
The second, setInterval() will execute the code on an interval of 1-second. So, your code will always execute every 1 second.
I'd recommend either removing the setTimeout() line inside of getTime(), or changing the setInterval() to a setTimeout() (to get the ball rolling, so to speak).
Related
I'll over simplify the problem in order to make it easier. I'm using the following Ajax script to call another .php file and have it return the results to the original page. I'm using Apache offline and the page is unfortunately returning blank.
<html>
<head>
<script>
function showInfo(str) {
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("result").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","practice.php?q="+str,true);
xmlhttp.send();
}
window.onload = function() { showInfo('bleh'); };
</script>
</head>
<body>
<div id="result"></div>
</body>
//Then the code below is another file called practice.php, which corresponds the ajax above
<?
$test = $_GET['q'];
echo $test;
?>
I am pretty sure $_GET is a case-sensitive variable name on most OSes, so $_Get would be empty.
I would comment if I could -
What happens when you try to hit the page directly (ie put practice.php?q=test) in the browser?
Also I can't find any documentation (it's hard to google it), but it wouldn't hurt to make the opening tag <?php instead of just <?
Right up front...I am very new to using Ajax.
I'm working on a web site where I want the results of one Select object to determine the options in the second Select object(from a database query). I'm using PHP and it appears that the only way to do this is to use Ajax. I've written a short html page to test my Ajax knowledge and it seems to work just find on Firefox but not on Chrome or IE. I've done a lot of research and found all sorts of folks with similar problems but no real solution.
I'm making the XMLHTTPRequest call to a local file in the same folder even so I should not be experiencing any cross-domain problems. Any help would be greatly appreciated.
Here's my Javascript function that gets called when the Select box is changed:
...
function getData(str)
{
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.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
alert(xmlhttp.responseText);
}
********ajax_info.php
+++++++++++++++++++++
//this is the php file that runs in response to the xmlhttprequest. It just generates a string of number at this time.
<?php
$str = "";
$i = 0;
for($i; $i<1000; $i++)
{
$str = $str.$i."-";
}
echo $str;
?>
You need to attach an event handler to your xmlhttp object to catch the onreadystatechange event. Note that when you alert your value, the asynchronous ajax call has just fired and has not finished yet (you are not checking for that anyway):
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
Well in that case you should try jQuery. It will be lot easier for you to make ajax request.
Here is an example for your problem
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// FOR GET REQUEST
$.get("ajax_info.php",{color:'value'},function(data) {
alert(data); // RETRIEVE THE RESULT
});
</script>
I will break this question into paragraphs for easier reference.
I have a script that calls a php file using Ajax; the script is executed once a button is pressed.
The PHP file contains a simple code that plusses a number with 1.
<?php
$response = $response + 1;
echo $response;
?>
However, something goes wrong when the button is pressed multiple times. I have done some research and I can conclude that there is either something wrong with the simple PHP script that I have made, or the code is only executed once per page reload.
I read an article explaining a lot of work using Javascript if I want an Ajax command to execute multiple times during the same script but I don't see the reason that it can't execute multiple times already when the button is pressed.
Question: Is the PHP file "post.php" even getting executed everytime the button is pressed? Is it something with my PHP file?
How can I make the script plus the number by 1 everytime the button is pressed? And is it because I need some extra Javascript to do that?
The rest of the script is here:
<head>
<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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","post.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<p>This button will execute an Ajax function</p>
<button type="button" onclick="loadXMLDoc()">Press here!</button>
<div id="myDiv"></div>
<script type="text/javascript" src="http://www.parameter.dk/counter/5b0d9873158158e08cad4c71256eb27c"></script>
</body>
If I wasn't clear enough at some point, please pick out the paragraph number and I'll deepen that part.
In your code $response is always 1 because php by default have no state. You can fix it by saving response inside a session.
session_start();
if (isset($_SESSION['response'])) {
$_SESSION['response'] = $_SESSION['response'] + 1;
} else {
$_SESSION['response'] = 1;
}
echo $_SESSION['response'];
please, I need an ajax script that will add to the count of unread messages without a full page refresh and subtract onclick of a message.
Something very similar to inbox messages count in most email clents.
I will truly appreciate any useful help.
Thank you
Use javascript's setInterval function to check whether an unread message is available. Example:
setInterval(function() {
// ajax request to check for unread messages
}, 1000);
The ajax check in the above example will execute in every 1 second (1000 milliseconds). You can change the interval as you like, say 5000 (5 seconds).
Make a function that can call different php files.
function useAjax(url1, area, send1)
{
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(area).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(POST,url,true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(send1);//to send post values "id="+id+"&message="+message"
return false;
}
So you could use this function to call "get_messages.php" or "read_message.php" and set the Post vaules accordingly
I made this little script with tutorials on internet. php function calls this javascript as many times as there are buttons (foreach), right now i have three. $value is the div name of specific button (buttons are stored in php array).
Everything works fine... except when i click through all the buttons fast, the loading gif remains without javascript changing the button status. The response, witch it gets from another php is the new button state and session variable change. Session variable gets changed but the div dosent.
So, heres where i need help, how can i make it so, when i click buttons fast, the div gets changed too?
my code
function load_javascripts() {
foreach ($GLOBALS["VARIABLES"]["button_list"] as $key => $value) {
$scripts .= "
function run_alias_button_".$value."(str)
{
document.getElementById('aliasbutton_".$value."').innerHTML='<img src=ajax_loader.gif>';
if (str=='')
{
document.getElementById('aliasbutton_".$value."').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)
{
document.getElementById('aliasbutton_".$value."').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','?leht=alias_logimine&alias=".$value."',true);
xmlhttp.send();
}
";
}
return $scripts;
}
Put var xmlhttp; at the very beginning of the function, making the variable explicitly local. Sometimes without that statement browsers may try to find a global variable with this name and readystate monitoring is shifted from one request to another.
Just a tip. Use the open function always before the onreadystatechange event. The way you using may works on firefox but IE doens't understand. LIke this:
xmlhttp.open('GET','?leht=alias_logimine&alias=".$value."',true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('aliasbutton_".$value."').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send();