Tuesday, March 28, 2017

How can we load PHP file into DIV by jQuery?




In this tutorial, I am going to show you, How we can load .php file using jquery.
To load .php file, we simply use load() function to call php file in a div.

Here is the example how i load php file with jquery load() function


 Database Name: `load`

Table structure for table `categories`

CREATE TABLE IF NOT EXISTS `categories` (
  `cat_id` int(100) NOT NULL,
  `cat_title` varchar(500) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;

 Dumping data for table `categories`
 

INSERT INTO `categories` (`cat_id`, `cat_title`) VALUES
(3, 'What is html?'),
(4, 'What is css?'),
(5, 'What is php?\r\n'),
(10, 'What is linux?'),
(13, 'toit');

db.php

  1. <?Php
  2.     $dbhost = 'localhost';
  3.     $dbname = 'load';  
  4.     $dbuser = 'root';                  
  5.     $dbpass = ''; 
  6.     
  7.     try{
  8.         
  9.         $dbcon = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
  10.         $dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  11.         
  12.     }catch(PDOException $ex){
  13.         
  14.         die($ex->getMessage());
  15.     }
  16.     
  17. ?>

index.php

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>onlinestudy.bramento.com</title>
  6. <script type="text/javascript">
  7. $(document).ready(function() {
  8.     $("#results").load("getcat.php");  //using load() functions here 
  9.     
  10. });
  11. </script>
  12. </head>
  13. <h1> How we can load .php file using jquery.</h1>
  14. <div id="results"></div>
  15. <body>
  16. </body>
  17. </html>

 getcat.php

  1. <?php
  2.         require_once 'db.php';  
  3.         $stmt = $dbcon->prepare('SELECT * FROM categories');
  4.         $stmt->execute();
  5.         
  6.         while($row=$stmt->fetch(PDO::FETCH_ASSOC))
  7.         {
  8.             extract($row);
  9.             ?>         
  10.        <p> <?php echo $row['cat_title']; ?></p>
  11.             <?php
  12.         }
  13.         ?>

No comments:

Post a Comment