AJAX refresh!! where to put the timer?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • canabatz
    New Member
    • Oct 2008
    • 155

    AJAX refresh!! where to put the timer?

    Hello , i got this code that works great , now i want to have it refresh every 4 seconds , where can i put the timer to do that?

    i realy need help!!

    thanx!!


    Code:
    <script type="text/javascript">
    //Global vars to hold connection to web pages
    var request;
    
    function getHTTPObject() 
    {
        var xhr = false;
        if (window.XMLHttpRequest) 
        {
            xhr = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            try 
            {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } 
            catch(e) 
            {
                try 
                {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                } 
                catch(e) 
                {
                    xhr = false;
                }
            }
        }
        return xhr;
    }
    
    var xmlHttp
    var xmlHttp2
    
    function showPage(str) { 
    	//Function that gets called
    	//Currently we only call one other sub, but this could change
    	showStates(str)
    }
    
    
    function showStates(str) { 
    	//This sub will populate a table with all the states and get the 
    	//pagination built
    	
    	//Make the AJAX connection for both the navigation and content
    	xmlHttp=GetXmlHttpObject()
    	xmlHttp2=GetXmlHttpObject()
    	
    	//If we cant do the request error out
    	if (xmlHttp==null || xmlHttp2==null ) {
    	 	alert ("Browser does not support HTTP Request")
    	 	return
    	}
    		
    	//First build the navigation panel
    	var url="getuser.php?bid_id=<?=$bid_id;?>"
    	url=url+"&p="+str
    	url=url+"&t=nav"
    	url=url+"&sid="+Math.random()
    
    	//Once the page finished loading put it into the div
    	xmlHttp2.onreadystatechange=navDone 
    
    	//Get the php page
    	xmlHttp2.open("GET",url,true)
    	xmlHttp2.send(null)
    	
    	//Build the url to call
    	//Pass variables through the url
    	var url="getuser.php?bid_id=<?=$bid_id;?>"
    	url=url+"&p="+str
    	url=url+"&t=con"
    	url=url+"&sid="+Math.random()
    	
    	//Once the page finished loading put it into the div
    	xmlHttp.onreadystatechange=stateChanged 
    	
    	//Get the php page
    	xmlHttp.open("GET",url,true)
    	xmlHttp.send(null)
    	
    	
    }
    
    function navDone() { 
    	//IF this is getting called when the page is done loading then fill the pagination div
    	if (xmlHttp2.readyState==4 || xmlHttp2.readyState=="complete") { 
    	 	//Update the Div tag with the outputted text
    	 	document.getElementById("pgNavigation").innerHTML=xmlHttp2.responseText 
    	} 
    }
    
    function stateChanged() { 
    	//IF this is getting called when the page is done loading the states then output the div
    	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { 
    	 	//Update the Div tag with the outputted text
    	 	document.getElementById("pgContent").innerHTML=xmlHttp.responseText 
    	} 
    }
    
    function GetXmlHttpObject() {
    	//Determine what browser we are on and make a httprequest connection for ajax
    	var xmlHttp=null;
    
    	try {
    	 	// Firefox, Opera 8.0+, Safari
    	 	xmlHttp=new XMLHttpRequest();
    	}
    	catch (e) {
    	 	//Internet Explorer
    	 	try {
    	  		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    	  	}
    	 	catch (e) {
    	  		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    	  	}
    	}
    	
    	return xmlHttp;
    }
    
    function plusOne() {
    	//This is just a second counter to prove that we arent refreshing 
    	// If using the content ('childNode') of an id element...
    	var spanEl = document.getElementById('spanEl');
    	spanEl.childNodes[0].nodeValue = ( parseInt(spanEl.childNodes[0].nodeValue) + 1 );
    }
    
    //Creates a timer 
    
    
    //Starts the counter
    window.onload = plusOne;
    
    //Onload start the user off on page one
    window.onload = showPage("1");
    
    </script>
  • canabatz
    New Member
    • Oct 2008
    • 155

    #2
    i fixed it thanx1!!!! :)

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      Though I have an idea how you did, can you post how you solved it? It may help someone else who comes across this thread looking for a solution to a similar problem.

      Comment

      • canabatz
        New Member
        • Oct 2008
        • 155

        #4
        The true :) ,it did solve one thing to refresh the content ,but it didnt solve the all thing i needed,

        i just put the setTimeout in the right position ,and it did refresh , but it was doing refresh and bring me all the time to the first page!! (im using it with pagination from mysql database)

        what i did:

        Code:
        function showPage(str) { 
          //Function that gets called
          //Currently we only call one other sub, but this could change
          showStates(str)
        setTimeout('showPage("1")', 4000);
         }
        i hope it will help some one!!

        and maybe some one can help me to solve it to stay in the next page with refreshing also!!
        Last edited by acoder; Oct 30 '08, 07:21 AM. Reason: Added [code] tags

        Comment

        • acoder
          Recognized Expert MVP
          • Nov 2006
          • 16032

          #5
          That's because you're always calling it with "1". Use an integer and update it each time you make the call. Note that you can use setInterval in place of setTimeout.

          Comment

          • canabatz
            New Member
            • Oct 2008
            • 155

            #6
            this is the 2 files im using ,maybe some one can take a look at them and tell me what im doing wrong! or what to do!!
            Code:
            <script type="text/javascript">
            //Global vars to hold connection to web pages
            
            
            var request;
            
            function getHTTPObject() 
            {
                var xhr = false;
                if (window.XMLHttpRequest) 
                {
                    xhr = new XMLHttpRequest();
                } else if (window.ActiveXObject) {
                    try 
                    {
                        xhr = new ActiveXObject("Msxml2.XMLHTTP");
                    } 
                    catch(e) 
                    {
                        try 
                        {
                            xhr = new ActiveXObject("Microsoft.XMLHTTP");
                        } 
                        catch(e) 
                        {
                            xhr = false;
                        }
                    }
                }
                return xhr;
            }
            
            var xmlHttp
            var xmlHttp2
            
            function showPage(str) { 
            	//Function that gets called
            	//Currently we only call one other sub, but this could change
            	showStates(str)
            		
            		
            }
            
            
            function showStates(str) { 
            	//This sub will populate a table with all the states and get the 
            	//pagination built
            	
            
            	//Make the AJAX connection for both the navigation and content
            	xmlHttp=GetXmlHttpObject()
            	xmlHttp2=GetXmlHttpObject()
            	
            	//If we cant do the request error out
            	if (xmlHttp==null || xmlHttp2==null ) {
            	 	alert ("Browser does not support HTTP Request")
            	 	return
            	}
            	
            
            	//First build the navigation panel
            	var url="getuser.php?bid_id=<?=$bid_id;?>"
            	url=url+"&p="+str
            	url=url+"&t=nav"
            	url=url+"&sid="+Math.random()
            
            	//Once the page finished loading put it into the div
            	xmlHttp2.onreadystatechange=navDone 
            
            	//Get the php page
            	xmlHttp2.open("GET",url,true)
            	xmlHttp2.send(null)
            	
            	//Build the url to call
            	//Pass variables through the url
            	var url="getuser.php?bid_id=<?=$bid_id;?>"
            	url=url+"&p="+str
            	url=url+"&t=con"
            	url=url+"&sid="+Math.random()
            	
            	//Once the page finished loading put it into the div
            	xmlHttp.onreadystatechange=stateChanged 
            	
            	//Get the php page
            	xmlHttp.open("GET",url,true)
            	xmlHttp.send(null)
            
            	
            }
            
            function navDone() { 
            	//IF this is getting called when the page is done loading then fill the pagination div
            	if (xmlHttp2.readyState==4 || xmlHttp2.readyState=="complete") { 
            	 	//Update the Div tag with the outputted text
            	 	document.getElementById("pgNavigation").innerHTML=xmlHttp2.responseText 
            	} 
            }
            
            function stateChanged() { 
            	//IF this is getting called when the page is done loading the states then output the div
            	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { 
            	 	//Update the Div tag with the outputted text
            	 	document.getElementById("pgContent").innerHTML=xmlHttp.responseText 
            	} 
            }
            
            function GetXmlHttpObject() {
            	//Determine what browser we are on and make a httprequest connection for ajax
            	var xmlHttp=null;
            
            	try {
            	 	// Firefox, Opera 8.0+, Safari
            	 	xmlHttp=new XMLHttpRequest();
            	}
            	catch (e) {
            	 	//Internet Explorer
            	 	try {
            	  		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
            	  	}
            	 	catch (e) {
            	  		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            	  	}
            	}
            	
            	return xmlHttp;
            }
            
            
            
            //Onload start the user off on page one
            window.onload = showPage("1");
            
            
            </script>
            Code:
            //############################################
            //First get the page value passed to this page
            $pageNum='';
            if (isset($_GET["p"])) {
            	$pageNum=$_GET["p"];
            }
            
            $type='';
            if (isset($_GET["t"])) {
            	$type=$_GET["t"];
            }
            
            //############################################
            //Now import the settings
            header('Content-Type: text/html; charset=windows-1255');
            include("conn.php");
            $RPP=50;
            
            $PrevIc=		"images/bprv.gif";
            $FirstIc=		"images/bfrst.gif";
            $NextIc=		"images/bnxt.gif";
            $LastIc=		"images/blst.gif";
            
            $dPrevIc=		"images/dprv.gif";
            $dFirstIc=		"images/dfrst.gif";
            $dNextIc=		"images/dnxt.gif";
            $dLastIc=		"images/dlst.gif";
            //############################################
            //Connect to the db
            
            //############################################
            //Get a quick count of all the rows
            $querys   = "SELECT * FROM bidding_details where bid_id=$bid_id";
            $results  = mysql_query($querys);
            $num=mysql_num_rows($results);
            
            //############################################
            //If there are some rows then start the pagination
            if ($num>0) {
            	//Determine the maxpage and the offset for the query
            	$maxPage = ceil($bid_id/$RPP);
            	$offset = ($pageNum - 1) * $RPP;
            
            	//Initiate the navigation bar
            	$nav  = '';
            
            	//get low end
            	$page = $pageNum-3;
            
            	//get upperbound
            	$upper =$pageNum+3;
            
            	if ($page <=0) {
            		$page=1;
            	}
            
            	if ($upper >$maxPage) {
            		$upper =$maxPage;
            	}
            
            	//Make sure there are 7 numbers (3 before, 3 after and current
            	if ($upper-$page <6){
            
            		//We know that one of the page has maxed out
            		//check which one it is
            		//echo "$upper >=$maxPage<br>";
            		if ($upper >=$maxPage){
            			//the upper end has maxed, put more on the front end
            			//echo "to begining<br>";
            			$dif =$maxPage-$page;
            			//echo "$dif<br>";
            				if ($dif==3){
            					$page=$page-3;
            				}elseif ($dif==4){
            					$page=$page-2;
            				}elseif ($dif==5){
            					$page=$page-1;
            				}
            		}elseif ($page <=1) {
            			//its the low end, add to upper end
            			//echo "to upper<br>";
            			$dif =$upper-1;
            
            			if ($dif==3){
            				$upper=$upper+3;
            			}elseif ($dif==4){
            				$upper=$upper+2;
            			}elseif ($dif==5){
            				$upper=$upper+1;
            			}
            		}
            	}
            
            	if ($page <=0) {
            		$page=1;
            	}
            
            	if ($upper >$maxPage) {
            		$upper =$maxPage;
            	}
            
            	//These are the numbered links
            	for($page; $page <=  $upper; $page++) {
            		if ($page == $pageNum){
            			//If this is the current page then disable the link
            			$nav .= "$page";
            			
            		}else{
            			//If this is a different page then link to it
            			$nav .= " <a onclick='showPage(\"".$page."\")'>$page</a> ";
            		}
            	}
            
            
            
            	if ($maxPage>1 AND $type=='nav') {
            		// print the navigation link
            		echo $first . $prev . $nav . $next . $last;
            	}elseif ($maxPage>1 AND $type=='con') {
            		//Build the header
            		echo "<table width='517' border='0' cellspacing='0' cellpadding='0'>";
            		echo "	<tr>";
            		echo "<td align='center' width='90' bgcolor='#FF9900'>לקוח</td>";
            echo "<td align='center' width='90' bgcolor='#FF9900'>שם</td>";
            echo "<td align='center' width='90' bgcolor='#FF9900'>עיר</td>";
            echo "<td align='center' width='90' bgcolor='#FF9900'>הצעה</td>";
            echo "<td align='center' width='90' bgcolor='#FF9900'>מיקום</td>";
            		echo "	</tr>";
            
            		//Get all the rows
            the first file is the ajax script to call the second file ,the second file is calling the ddatabase for the records ,my problem is with the pagination ,if i put setTimeout to refresh the page it's returning back to the first page after the amount of time i put in the setTime out!!

            what can i do to keep refreshing the current page im in to!!

            thanx

            Comment

            • acoder
              Recognized Expert MVP
              • Nov 2006
              • 16032

              #7
              When you mention "current page", is it a paginated view, e.g. the URL has a page number as a parameter?

              Note that your onload is incorrect. It should be something like:
              Code:
              window.onload = function() {
                  setInterval(showPage,4000);
              }
              You could have the page number as a global variable which can be incremented in showPage.

              Comment

              • canabatz
                New Member
                • Oct 2008
                • 155

                #8
                it is pagination ,i put the onload you told me ,but when im going to page No 2 for example ,it's jumpijng back to page 1 ,after 4 seconds!

                im not so good in php and javascript :)

                i try so many combinations and it keep jumping to page one!!

                thanx for youe help!

                Comment

                • acoder
                  Recognized Expert MVP
                  • Nov 2006
                  • 16032

                  #9
                  OK, on the first page when you're on page 2, what's the full page URL including after the ?

                  Comment

                  • canabatz
                    New Member
                    • Oct 2008
                    • 155

                    #10
                    this is the problem:

                    window.onload = showPage("1");

                    the 1 is a connection for the +str that is reloading the page no 1

                    when it's like that window.onload = showPage("1"); ,i can navigate with the links ,but i want to have it refresh also if there is new data!!

                    this the url with all: for content

                    var url="getuser.ph p?bid_id=<?=$bi d_id;?>"
                    url=url+"&p="+s tr
                    url=url+"&t=con "
                    url=url+"&sid=" +Math.random()

                    this the url with all: for navigation

                    var url="getuser.ph p?bid_id=<?=$bi d_id;?>"
                    url=url+"&p="+s tr
                    url=url+"&t=nav "
                    url=url+"&sid=" +Math.random()

                    i removed the onload you wrote me , so now its without it

                    this is the link for example how it is now ,without settimeout or iterval

                    Comment

                    • acoder
                      Recognized Expert MVP
                      • Nov 2006
                      • 16032

                      #11
                      In your link, there's no page number, so how would it be reflected if you were on page 2? In other words, how do you get onto the second page? Is there a link on the page, or do you want this to happen automatically after 4 seconds?

                      Comment

                      • canabatz
                        New Member
                        • Oct 2008
                        • 155

                        #12
                        look at the bottom of the results ,its there

                        5,4,3,2,1 in red

                        i want the current page im in to be auto refresh after 4 seconds.

                        Comment

                        • acoder
                          Recognized Expert MVP
                          • Nov 2006
                          • 16032

                          #13
                          Oh, I see. These links are to showPage with the correct page number.

                          What you can do is add a global variable, pageno which is set to 1 initially. Then in the links, set this variable to the corresponding number. In the meantime, showPage will be called every 4 seconds using setInterval.

                          Comment

                          • canabatz
                            New Member
                            • Oct 2008
                            • 155

                            #14
                            if i knew how to do it ,it was good then !
                            im not this good in JS or PHP :)

                            :(

                            thanx alot!!

                            Comment

                            • acoder
                              Recognized Expert MVP
                              • Nov 2006
                              • 16032

                              #15
                              You only need to make a few changes.

                              1. Change window.onload to what I posted earlier.

                              2. Change showPage() to accept 0 parameters: function showPage() {

                              3. Add a global variable pageno which will be used in place of that parameter:
                              Code:
                              var pageno = 1;
                              4. Replace str in showPage() with pageno.

                              5. Change the links to set pageno instead of calling showPage:
                              Code:
                              <a href="#" onclick="pageno = 2; return false;">2</a>

                              Comment

                              Working...