• We just launched and are currently in beta. Join us as we build and grow the community.

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

bibil

Package Manager Expert
B Rep
0
0
0
Rep
0
B Vouches
0
0
0
Vouches
0
Posts
137
Likes
66
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
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

    [url=http://dev.mysql.com/doc/refman/%35%2E%31/en/control-flow-functions.html]IF

    NOT

    EXISTS

    [/url] `add_

    delete_

    record`

    (
  2. `id`

    int

    (

    11

    )

    NOT

    NULL

    AUTO_INCREMENT

    ,
  3. `content`

    text

    NOT

    NULL

    ,
  4. PRIMARY KEY

    (

    `id`

    )
  5. )

    ENGINE

    =

    InnoDB

    DEFAULT

    CHARSET

    =

    latin1 AUTO_INCREMENT

    =

    0

    ;

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. <script type="text/javascript">
  7. $(document).ready(function() {

  8. //##### Add record when Add Record Button is click #########
  9. $("#content-form").submit(function (e) {
  10. e.preventDefault();
  11. if($("#contentText").val()==='')
  12. {
  13. alert("Please enter some text!");
  14. return false;
  15. }
  16. var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
  17. jQuery.ajax({
  18. type: "POST", // Post / Get method
  19. url: "response.php", //Where form data is sent on submission
  20. dataType:"text", // Data type, HTML, json etc.
  21. data:myData, //Form variables
  22. success:function(response){
  23. $("#responds").append(response);
  24. $('#contentText').val("")
  25. },
  26. error:function (xhr, ajaxOptions, thrownError){
  27. alert(thrownError);
  28. }
  29. });
  30. });

  31. });
  32. </script>
  33. <style>
  34. .form_style #textarea {
  35. border: 1px solid #CCCCCC;
  36. }

  37. .form_style #FormSubmit {
  38. display: block;
  39. background: #003366;
  40. border: 1px solid #000066;
  41. color: #FFFFFF;
  42. margin-top: 5px;
  43. }
  44. #responds{
  45. margin: 0px;
  46. padding: 0px;
  47. list-style: none;
  48. width:100%;
  49. }
  50. #responds li{
  51. list-style: none;
  52. padding: 10px;
  53. background: #D1CFCE;
  54. margin-bottom: 5px;
  55. border-radius: 5px;
  56. font-family: arial;
  57. font-size: 13px;
  58. }
  59. .del_wrapper{float:right;}.content_wrapper {
  60. width: 500px;
  61. margin-right: auto;
  62. margin-left: auto;
  63. }
  64. .item-list{
  65. text-align: left;
  66. }
  67. #contentText{
  68. width: 100%;
  69. }
  70. </style>
  71. </head>
  72. <body align="middle">
  73. <h3><strong>Save and Load Data without leaving the page using PHP and Ajax</strong></h3>
  74. <hr>
  75. <div class="content_wrapper">
  76. <div class="form_style">

  77. <form id="content-form">
  78. <textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
  79. <br>
  80. <button id="FormSubmit">Add record</button>
  81. </form>
  82. <br>
  83. </div>
  84. <ul id="responds">
  85. <?php
  86. //include db configuration file
  87. include_once

    (

    "config.php"

    )

    ;

  88. //MySQL query
  89. $Result

    =

    mysqli_query

    (

    $connecDB

    ,

    "SELECT id,content FROM add_delete_record"

    )

    ;

  90. //get all records from add_delete_record table
  91. while

    (

    $row

    =

    mysqli_fetch_array

    (

    $Result

    )

    )
  92. {
  93. echo

    '<li id="item_'

    .

    $row

    [

    "id"

    ]

    .

    '" class="item-list">'

    ;
  94. echo

    $row

    [

    "content"

    ]

    .

    '</li>'

    ;
  95. }

  96. //close db connection
  97. ?>
  98. </ul>
  99. </div>
  100. </body>
  101. </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. $connecDB

    =

    mysqli_connect

    (

    $hostname

    ,

    $username

    ,

    $password

    ,

    $databasename

    )

    or die

    (

    'Could not connect to the database'

    )

    ;
  7. ?>

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. if

    (

    isset

    (

    $_POST

    [

    "content_txt"

    ]

    )

    &&

    strlen

    (

    $_POST

    [

    "content_txt"

    ]

    )

    >

    0

    )
  5. {
  6. $contentToSave

    =

    filter_var

    (

    $_POST

    [

    "content_txt"

    ]

    ,

    FILTER_SANITIZE_STRING,

    FILTER_FLAG_STRIP_HIGH)

    ;

  7. if

    (

    mysqli_query

    (

    $connecDB

    ,

    "INSERT INTO add_delete_record(content) VALUES('$contentToSave

    ')"

    )

    )
  8. {
  9. $my_id

    =

    mysqli_insert_id

    (

    $connecDB

    )

    ;
  10. echo

    '<li id="item_'

    .

    $my_id

    .

    '" class="item-list">'

    ;
  11. echo

    $contentToSave

    .

    '</li>'

    ;

  12. }

  13. }
  14. ?>

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.


Download
You must upgrade your account or reply in the thread to view hidden text.
 

452,292

323,526

323,535

Top