Skip to main content

How to Save and Load Data from Database Without refreshing the page using PHP and Ajax

Screenshot
Body

Hi everyone, The feature of this tutorial is it allows you to save data to the database and display data from the database without refreshing the page. I used Ajax and PHP in this tutorial. Our goal for this tutorial is to create a simple web application that has a simple form that will result an automatic load the data after the success response of saving the data. To start the coding let's follow the steps provided below.

Requirements:

  • Download and Install any local web-server such as XAMPP/WAMP.

Step 1: Creating Our Database

To create a database:
  1. If you are using XAMPP/WAMP, open the XAMPP/WAMP's Control Panel and strat "Apache" and "MySQL".
  2. Open PHPMyAdmin in a web browser. [http://localhost/phpmyadmin]
  3. Create a new database naming "ajaxphp".
  4. After creating a database name, click the SQL and paste the below code.
  1. CREATE TABLE IF NOT EXISTS `add_delete_record` (
  2. `content` text NOT NULL,
  3. PRIMARY KEY (`id`)

Step 2: Creating Our Form

In this we will create our form that display the data from database. To create our form copy the code below and save it as "index.php".

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <title>Save and load data without leaving the page using PHP and Ajax</title>
  5. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
  6.  
  7. <script type="text/javascript">
  8. $(document).ready(function() {
  9.  
  10. //##### Add record when Add Record Button is click #########
  11. $("#content-form").submit(function (e) {
  12. e.preventDefault();
  13. if($("#contentText").val()==='')
  14. {
  15. alert("Please enter some text!");
  16. return false;
  17. }
  18. var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
  19. jQuery.ajax({
  20. type: "POST", // Post / Get method
  21. url: "response.php", //Where form data is sent on submission
  22. dataType:"text", // Data type, HTML, json etc.
  23. data:myData, //Form variables
  24. success:function(response){
  25. $("#responds").append(response);
  26. $('#contentText').val("")
  27. },
  28. error:function (xhr, ajaxOptions, thrownError){
  29. alert(thrownError);
  30. }
  31. });
  32. });
  33.  
  34. });
  35. </script>
  36. <style>
  37. .form_style #textarea {
  38. border: 1px solid #CCCCCC;
  39. }
  40.  
  41. .form_style #FormSubmit {
  42. display: block;
  43. background: #003366;
  44. border: 1px solid #000066;
  45. color: #FFFFFF;
  46. margin-top: 5px;
  47. }
  48. #responds{
  49. margin: 0px;
  50. padding: 0px;
  51. list-style: none;
  52. width:100%;
  53. }
  54. #responds li{
  55. list-style: none;
  56. padding: 10px;
  57. background: #D1CFCE;
  58. margin-bottom: 5px;
  59. border-radius: 5px;
  60. font-family: arial;
  61. font-size: 13px;
  62. }
  63. .del_wrapper{float:right;}.content_wrapper {
  64. width: 500px;
  65. margin-right: auto;
  66. margin-left: auto;
  67. }
  68. .item-list{
  69. text-align: left;
  70. }
  71. #contentText{
  72. width: 100%;
  73. }
  74. </style>
  75. </head>
  76. <body align="middle">
  77. <h3><strong>Save and Load Data without leaving the page using PHP and Ajax</strong></h3>
  78. <hr>
  79. <div class="content_wrapper">
  80. <div class="form_style">
  81.  
  82. <form id="content-form">
  83. <textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
  84. <br>
  85. <button id="FormSubmit">Add record</button>
  86. </form>
  87. <br>
  88. </div>
  89. <ul id="responds">
  90. <?php
  91. //include db configuration file
  92. include_once("config.php");
  93.  
  94. //MySQL query
  95. $Result = mysqli_query($connecDB,"SELECT id,content FROM add_delete_record");
  96.  
  97. //get all records from add_delete_record table
  98. while($row = mysqli_fetch_array($Result))
  99. {
  100. echo '<li id="item_'.$row["id"].'" class="item-list">';
  101. echo $row["content"].'</li>';
  102. }
  103.  
  104. //close db connection
  105. ?>
  106. </ul>
  107. </div>
  108. </body>
  109. </html>

Step 3: Create Our Database Connection

Copy the code bellow and save it as "config.php".

  1. <?php
  2. $username = "root"; //mysql username
  3. $password = ""; //mysql password
  4. $hostname = "localhost"; //hostname
  5. $databasename = 'ajaxphp'; //databasename
  6.  
  7. $connecDB = mysqli_connect($hostname, $username, $password, $databasename)or die('Could not connect to the database');
  8. ?>

Step 4: Writing Our Save Script

In this step we write the code that save the data without loading the page. Copy the code bellow and save it as "response.php".

  1. <?php
  2. //include db configuration file
  3. include_once("config.php");
  4.  
  5. if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0)
  6. {
  7. $contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
  8.  
  9. if(mysqli_query($connecDB,"INSERT INTO add_delete_record(content) VALUES('$contentToSave')"))
  10. {
  11. $my_id = mysqli_insert_id($connecDB);
  12. echo '<li id="item_'.$my_id.'" class="item-list">';
  13. echo $contentToSave.'</li>';
  14.  
  15. }
  16.  
  17. }
  18. ?>

That's all you've successfully created your system that saves and displays data from the database without refreshing the page. Thank you for always following and giving positive comments for my tutorials.

Add new comment