Load data via Ajax


Ajax is very popular javascript framework widely used for better user experience and fast development process and its also easy to use. In this tutorial I will show you how to fetch data after page has been loaded from a database table using jQuery/Ajax.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
   <html>
   <head>
   <title></title>
   <meta name="" content="">
   <style>.msg{ color:#ff0000;}
   #contentloader{ background-color:#fff; border:1px solid #333; padding:10px; }
   .active { background-color: #0d9cf2}</style>
   </head>
   <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

Javascript function ajaxContentLoad() will be called on page load and it therefore calls ajaxData.php file sending page=Home as post data.
<script>

function ajaxContentLoad(page){
        q = {
      'page':page,
     }
        $.ajax({
      type:'post',
      data:q,
      url:'ajaxData.php',
      beforeSend: function(){
       $("#msg").text("sending request to server...");
      },
      complete:function (){
       $("#msg").text("request received and loaded");
      },
      success:function(result, textStatus, jqXHR) {      
       $("#contentloader").html(result);
      },
      error: function(jqXHR, textStatus, errorThrown){
       alert(errorThrown);
      }
     })
     }
     $().ready(function(e){
      ajaxContentLoad('Home');
     })
     
</script>

Once data is received it will be displayed in div with id contentloader. See here success: is used which is executed when ajax request is completed and response is sent to caller function. You can also click on button to change the content of this div. On clicking this button will call again ajaxContentLoad() function with page name.

<body>
    <div style="padding: 20px; margin:20px auto; width:80%; background: #eee">
    <button id="btn1" value="Home" onclick="ajaxContentLoad('Home');">Home</button>
    <button id="btn1" value="About" onclick="ajaxContentLoad('About');">About</button>
    <p id="msg" class="msg"></p>
    
     <div id="contentloader">
      Content on page load
     </div>
    </div>
   </body>
   </html>

And here is ajaxData.php file where query runs to fetch data from a table.

<?php
    $q = htmlspecialchars($_REQUEST['page']);

    $con = mysqli_connect('localhost','root',admin,'demo');
    if (!$con) {
      die('Could not connect: ' . mysqli_error($con));
    }

    mysqli_select_db($con,"demo");
    
    $sql="SELECT * FROM tbl_content WHERE page = '".$q."' ORDER BY ID ASC";
    $result = mysqli_query($con,$sql);

    while($row = mysqli_fetch_array($result)) {
      echo '
'; echo $row['content']; echo "
"; } mysqli_close($con);?>
And here is mysql file used to store data.
CREATE TABLE IF NOT EXISTS `tbl_content` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `page` varchar(255) DEFAULT NULL,
  `content` text,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `tbl_content`
--

INSERT INTO `tbl_content` (`id`, `page`, `content`) VALUES
(1, 'Home', 'This is home page content'),
(2, 'About', 'This is about content');


Post a Comment