Klaus Jasper
Klaus Jasper

Reputation: 89

Update a div tag in AJAX

I got now a page that contains PHP code and I want to Update a specific div tag automaticlly every 3 or 2 seconds currently I update an empty div tag from an external php file butb I want to update from the same page, this is my code that update external file:

<script>
function Ajax(){
var xmlHttp;
    try{    
        xmlHttp=new XMLHttpRequest();
    }
    catch (e){
        try{
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e){
            try{
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e){
                alert("Oops!");
                return false;
            }
        }
    }

xmlHttp.onreadystatechange=function(){
    if(xmlHttp.readyState==4){
        document.getElementById('ReloadThis').innerHTML=xmlHttp.responseText;
        setTimeout('Ajax()',2000);
    }
}
xmlHttp.open("GET","page.php",true);
xmlHttp.send(null);
}

window.onload=function(){
    setTimeout('Ajax()',2000);
}

</script> 
<div id="ReloadThis"></div>

How can I update the code at the same page, for example I want to update this:

    <?php 
$query5= mysql_query("SELECT * FROM `table` ORDER BY `time` DESC")or die(mysql_error());
    while($arr = mysql_fetch_array($query5)){
    $num = mysql_num_rows($query5);
    $tst = $arr['names'];
    echo '<br>'; 
?>

Upvotes: 0

Views: 203

Answers (1)

Harshveer Singh
Harshveer Singh

Reputation: 4187

You can put your PHP code in the same file, just use query string xmlHttp.open("GET","yourFileName.php?action=updateDiv",true); for same file and then in PHP script check query string and return content according to that-

<?php
if(isset($_GET['action']))
{
    if($_GET['action'] == "updateDiv")
    {
        $query5= mysql_query("SELECT * FROM `table` ORDER BY `time` DESC")or   die(mysql_error());
        while($arr = mysql_fetch_array($query5)){
        $num = mysql_num_rows($query5);
        $tst = $arr['names'];
        echo '<br>';
        die();
    }
}
?>

Upvotes: 2

Related Questions