andrewarnier
andrewarnier

Reputation: 177

how to update a <div> when database have changed, with ajax php and mysql?

I really need to this. I want a way to make a div works like (real-time), when the database change automatic update the div.

so if i have a div with value of 5 and this value i got it from the database with mysql and fetched it out on a div with php,then I have to process the value from php by javascript, how can i make this div get to 6 when the value on the database really changed. here is my code (mysite.php):

<script type='text/javascript'>
//This javascript will load when the page loads.
jQuery(document).ready( function($){

        //Initialize the Google Maps
        var geocoder;
        var map;
        var markersArray = [];
        var infos = [];

        geocoder = new google.maps.Geocoder();
        var myOptions = {
              zoom: 8,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            }
        //Load the Map into the map_canvas div
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        //Initialize a variable that the auto-size the map to whatever you are plotting
        var bounds = new google.maps.LatLngBounds();

        //Initialize the encoded string       
        var encodedString;

        //Initialize the array that will hold the contents of the split string
        var stringArray = [];

        //Get the value of the encoded string from the hidden input
        encodedString = document.getElementById("encodedString").value;

        //Split the encoded string into an array the separates each location
        stringArray = encodedString.split("****");

        var x;
     for (x = 0; x < stringArray.length; x = x + 1)
        {
            var addressDetails = [];
            var marker;
            //Separate each field
            addressDetails = stringArray[x].split("&&&");
            //Load the lat, long data
            var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
            var image = new google.maps.MarkerImage(addressDetails[3]);

            //Create a new marker and info window
            var marker = new google.maps.Marker({
                map: map,
                icon: image,
                position: lat,
                content: addressDetails[0]
            });



            //Pushing the markers into an array so that it's easier to manage them
            markersArray.push(marker);
            google.maps.event.addListener( marker, 'click', function () {
                closeInfos();
                var info = new google.maps.InfoWindow({content: this.content});
                //On click the map will load the info window
                info.open(map,this);
                infos[0]=info;
            });




           //Extends the boundaries of the map to include this new location
           bounds.extend(lat);
        }
        //Takes all the lat, longs in the bounds variable and autosizes the map
        map.fitBounds(bounds);



        //Manages the info windows
        function closeInfos(){
       if(infos.length > 0){
          infos[0].set("marker",null);
          infos[0].close();
          infos.length = 0;
       }
        }

});
</script>

</head>
<body>
<div id='input'>

    <?php


    //Initialize your first couple variables
    $encodedString = ""; //This is the string that will hold all your location data
    $x = 0; //This is a trigger to keep the string tidy

    //Now we do a simple query to the database

    // DB  INFO CONNECTION IS HERE AND WORKS

    $result = mysql_query("SELECT * FROM `ulocation` WHERE `ul_lat`!='' AND `ul_long`!='' AND `ul_onduty`='1'",$db1);

    //Multiple rows are returned
    while ($row = mysql_fetch_array($result, MYSQL_NUM))
    {
        //This is to keep an empty first or last line from forming, when the string is split
        if ( $x == 0 )
        {
             $separator = "";
        }
        else
        {
             //Each row in the database is separated in the string by four *'s
             $separator = "****";
        }
        $status='0';
        $cadd  = sql::getval('cal_address', 'call', "WHERE    `cal_id`='$row[14]'");
        $num  = sql::getval('cal_num', 'call', "WHERE `cal_id`='$row[14]'");
        $pcond  = sql::getval('cal_pcond', 'call', "WHERE `cal_id`='$row[14]'");
        $list="$num $cadd";
        //Saving to the String, each variable is separated by three &'s
        $encodedString = $encodedString.$separator.
        "<table border=0 width='350' height='20' class='maincolm' cellpadding=0   cellspacing=0><td align=left valign=top><h2></h2></td><tr><td width=100%><font size=3  face=arial><p><b>".$row[2].
        "</b>".
        "<br>Address: $list".
        "<br>Call Type: $pcond".
        "<br><br>Lat: ".$row[5].
        "<br>Long: ".$row[6].
        "</td></table>".
        "</p>&&&".$row[5]."&&&".$row[6]."&&&".$row[8]."&&&".$row[14];
        $x = $x + 1;
    }        
    ?>

    <input type="hidden" id="encodedString" name="encodedString" value="<?php echo   $encodedString; ?>" />




  <? echo "<body oncontextmenu=\"return false\" style=\"overflow: hidden; \"   topmargin=0 leftmargin=0 rightmargin=0 bottommargin=0>";


  <div id=\"map_canvas\"></div>
  </body>
  </html>";

  ?>

Thanks, anyhelp

Upvotes: 0

Views: 6307

Answers (3)

andrewarnier
andrewarnier

Reputation: 177

i have try to add the code as follow that you suggest,

$(document).ready(function(){
setInterval(function(){
    $.ajax({
        url: 'mysite.php',
        dataType: 'json',
        success: function(response) {
            // Do some stuff
        }
    });
}, 5000);
});

then echo $encodedString that fetch from mysql ,i found value didn't update when database have changed,

 <body>
<div id='input'>

    <?php


    //Initialize your first couple variables
    $encodedString = ""; //This is the string that will hold all your location data
    $x = 0; //This is a trigger to keep the string tidy

    //Now we do a simple query to the database

    // DB  INFO CONNECTION IS HERE AND WORKS

    $result = mysql_query("SELECT * FROM `ulocation` WHERE `ul_lat`!='' AND `ul_long`!='' AND `ul_onduty`='1'",$db1);

    //Multiple rows are returned
    while ($row = mysql_fetch_array($result, MYSQL_NUM))
    {
        //This is to keep an empty first or last line from forming, when the string is split
        if ( $x == 0 )
        {
             $separator = "";
        }
        else
        {
             //Each row in the database is separated in the string by four *'s
             $separator = "****";
        }
        $status='0';
        $cadd  = sql::getval('cal_address', 'call', "WHERE    `cal_id`='$row[14]'");
        $num  = sql::getval('cal_num', 'call', "WHERE `cal_id`='$row[14]'");
        $pcond  = sql::getval('cal_pcond', 'call', "WHERE `cal_id`='$row[14]'");
        $list="$num $cadd";
        //Saving to the String, each variable is separated by three &'s
        $encodedString = $encodedString.$separator.
        "<table border=0 width='350' height='20' class='maincolm' cellpadding=0   cellspacing=0><td align=left valign=top><h2></h2></td><tr><td width=100%><font size=3  face=arial><p><b>".$row[2].
        "</b>".
        "<br>Address: $list".
        "<br>Call Type: $pcond".
        "<br><br>Lat: ".$row[5].
        "<br>Long: ".$row[6].
        "</td></table>".
        "</p>&&&".$row[5]."&&&".$row[6]."&&&".$row[8]."&&&".$row[14];
        $x = $x + 1;
    }        
    ?>

    <input type="hidden" id="encodedString" name="encodedString" value="<?php echo   $encodedString; ?>" />




  <? echo "<body oncontextmenu=\"return false\" style=\"overflow: hidden; \"   topmargin=0 leftmargin=0 rightmargin=0 bottommargin=0>";


  <div id=\"map_canvas\"></div>
  </body>
  </html>";

  ?>
</div>

Upvotes: 0

Canser Yanbakan
Canser Yanbakan

Reputation: 3870

You can't do it automatically like a listener without using a server side language like node.js.

See: http://nodejs.org/

But;

You can check the database every x seconds to see if any changes available with javascript.

Your code is messy, so i could not read what is going on...

To do that;

I suggest you to use a javascript framework / library like jQuery.

Using jquery ajax:

$(document).ready(function(){
    setInterval(function(){
        $.ajax({
            url: 'your-php-file.php',
            dataType: 'json',
            success: function(response) {
                // Do some stuff
            }
        });
    }, 5000);
});

Upvotes: 0

Abhijeet Dange
Abhijeet Dange

Reputation: 133

You have to implement an Ajax mechanism, there has to be an ajax call which runs periodically to get value from DB and update inner html of that particular div.

Upvotes: 1

Related Questions