🎓 Free Capstone Projects with Full Documentation, ER Diagrams & Source Code — Updated Weekly for 2026
👨‍💻 Free Source Code & Capstone Projects for Developers

Insert and Display Data in PHP & MYSQL Without Refreshening Page

This tutorial is all about Insert and Display Data in PHP & MYSQL Without Refreshening Page. In this tutorial you will learn Insert and Display Data in PHP & MYSQL Without Refreshening Page.

Good Day! Everyone! Today I’m going to teach you my inserting and displaying data in your database.

Unlike with my previous tutorial which is about a very simple way in inserting and showing data in database. Here, you don’t need to refresh your page in order to display the inserted data and we add some styles now.

So before you go with this tutorial, for the beginners, I suggest to start with my previous tutorial regarding simple way of inserting and displaying data in PHP. >> click here << to go my previous article.

So now, we will going to start our tutorial.

Make sure you already have the following. You can download it below:

jquery-3.2.1.min

bootstrap.min

bootstrap.min

Now, if you are already done downloading all the files below. Just go now to your browser then go to PHPMYADMIN to create a database.

Create a database then name it as any name you desire. In my case, I use “itsourcecode” as the name of the database.

Then create a table. Put “mydata” as the table name then put the following attributes.

CREATE TABLE `mydata` (`id` int(11) NOT NULL,
`name` text NOT NULL, `age` int(11) NOT NULL,
`gender` text NOT NULL, `birthday` date NOT NULL)
 ENGINE=MyISAM DEFAULT CHARSET=latin1;

Now for the connection to the database. Create a “connection.php” file then put the following codes.

<?php
 date_default_timezone_set('Asia/Manila');
 $servername = 'localhost';
 $username = 'root';
 $password = '';
 $dbname = 'itsourcecode';

try {
 $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 } catch (Exception $ex) {
 echo "Connection Failed: ". $ex->getMessage();
 }
 ?>

As you can see, we now upgraded our coding structure in managing our database using PDO. This is now the updated version in MYSQL.

Now, create a “index.php” file then put the following codes.

<!DOCTYPE html>
 <html>
 <head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Inserting Data Without Refreshing the Page</title>
 <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
 http://assets/js/jquery-3.2.1.min.js
 http://assets/js/bootstrap.min.js
 </head>
 <body>
<div class="container">
<h5>Inserting Data in PHP/MYSQL Without Refreshing the Page</h5>
<div class="row">
<div class="col-sm-3"><button class="btn btn-info btn-md" type="button">Add Data</button></div>
<p>&lt;/div&gt;</p>
<div class="row">
<table id="itemtable" class="table table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Birthday</th>
</tr>
</thead>
<tbody id="dataBody"></tbody>
</table>
</div>
<p>&lt;/div&gt;</p>
<p>&lt;!-- Start Add Data Modal --&gt;</p>
<div id="addDataModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"><button class="close" type="button">x</button><p></p>
<h4 class="modal-title">Add New Data</h4>
</div>
<p>&lt;form class="form-horizontal" id="add-form"&gt;</p>
<div class="modal-body">
<div class="form-group"><label class="control-label col-sm-2" for="name">Name:</label><p></p>
<div class="col-sm-10"></div>
<p>&lt;/div&gt;</p>
<div class="form-group"><label class="control-label col-sm-2" for="age">Age:</label><p></p>
<div class="col-sm-3"></div>
<p>&lt;/div&gt;</p>
<div class="form-group"><label class="control-label col-sm-2" for="gender">Gender:</label><p></p>
<div class="col-sm-3">
<p>-- Gender --<br>
Male<br>
Female</p>
</div>
<p>&lt;/div&gt;</p>
<div class="form-group"><label class="control-label col-sm-2" for="bday">Birthday:</label><p></p>
<div class="col-sm-4"></div>
<p>&lt;/div&gt;<br>
&lt;input type="hidden" name="action" value="addData"&gt;<br>
&lt;/div&gt;</p>
<div class="modal-footer"><button class="btn btn-primary" type="submit">Add</button><br>
<button class="btn btn-danger" type="button">Close</button></div>
<p>&lt;/form&gt;<br>
&lt;/div&gt;<br>
&lt;/div&gt;<br>
&lt;/div&gt;<br>
&lt;!-- End Add Data Modal --&gt;</p>
<p>// When the HTML or documents loads, Load datas in table.<br>
$(document).ready(function(){<br>
function showData() {<br>
$.ajax({<br>
url: 'dataFunctions.php',<br>
type: 'POST',<br>
data: {action : 'showData'},<br>
dataType: 'html',<br>
success: function(result)<br>
{<br>
$('#dataBody').html(result);<br>
},<br>
error: function()<br>
{<br>
alert('Failed!');<br>
}<br>
})<br>
}<br>
showData();<br>
});</p>
<p>//Add form submit handler<br>
$('#add-form').submit(function(e){<br>
e.preventDefault();<br>
$.ajax({<br>
url: 'dataFunctions.php',<br>
type: 'POST',<br>
data: $(this).serialize(),<br>
dataType: 'html',<br>
success: function(result)<br>
{<br>
$('#dataBody').html(result);<br>
$('#addDataModal').modal('toggle');<br>
},<br>
error: function()<br>
{<br>
alert('Failed!');<br>
}<br>
})<br>
});</p>
<p>&lt;/body&gt;<br>
&lt;/html&gt;</p>
<p>Then create a “<strong>dataFunctions.php</strong>” file then put the following codes. These are the functions in manipulating data in our database.</p>
<p>&lt;?php<br>
if (isset($_POST['action']) &amp;&amp; !empty($_POST['action'])) {<br>
$action = $_POST['action'];<br>
switch($action) {<br>
case 'addData':<br>
addData();<br>
break;<br>
case 'showData':<br>
displayData();<br>
break;<br>
default:<br>
# code...<br>
break;<br>
}<br>
}</p>
<p>function addData() {<br>
include 'connection.php';</p>
<p>$stmt = $conn-&gt;prepare("INSERT INTO mydata (name, age, gender, birthday) VALUES (:name, :age, :gender, :birthday)");</p>
<p>$name = $_POST['name'];<br>
$age = $_POST['age'];<br>
$gender = $_POST['gender'];<br>
$birthday = $_POST['bday'];</p>
<p>$stmt-&gt;bindParam(':name', $name);<br>
$stmt-&gt;bindParam(':age', $age);<br>
$stmt-&gt;bindParam(':gender', $gender);<br>
$stmt-&gt;bindParam(':birthday', $birthday);<br>
$stmt-&gt;execute();</p>
<p>displayData();<br>
}</p>
<p>function displayData() {<br>
include 'connection.php';</p>
<p>$data = $conn-&gt;query("SELECT * FROM mydata");</p>
<p>while ($r = $data-&gt;fetch()) {<br>
echo '&lt;tr&gt;';<br>
echo '&lt;td&gt;' . $r['name'] . '&lt;/td&gt;';<br>
echo '&lt;td&gt;' . $r['age'] . '&lt;/td&gt;';<br>
echo '&lt;td&gt;' . $r['gender'] . '&lt;/td&gt;';<br>
echo '&lt;td&gt;' . $r['birthday'] . '&lt;/td&gt;';<br>
echo '&lt;/tr&gt;';<br>
}<br>
}<br>
?&gt;</p>
<p><strong>Screenshots:</strong></p>
<figure><a href="//itsourcecode.com/wp-content/uploads/2017/05/4-1.png"><img class="wp-image-7688 aligncenter" src="//itsourcecode.com/wp-content/uploads/2017/05/4-1-300x135.png" alt="" width="340" height="153"></a></figure><p></p>
<figure><a href="//itsourcecode.com/wp-content/uploads/2017/05/3-1.png"><img class="wp-image-7687 aligncenter" src="//itsourcecode.com/wp-content/uploads/2017/05/3-1-300x132.png" alt="" width="345" height="152"></a></figure><figure><a href="//itsourcecode.com/wp-content/uploads/2017/05/2-1.png"><img class="wp-image-7686 aligncenter" src="//itsourcecode.com/wp-content/uploads/2017/05/2-1-300x134.png" alt="" width="345" height="154"></a></figure><p></p>
<figure><a href="//itsourcecode.com/wp-content/uploads/2017/05/1-1.png"><img class="wp-image-7685 aligncenter" src="//itsourcecode.com/wp-content/uploads/2017/05/1-1-300x134.png" alt="" width="340" height="152"></a></figure><p></p>
<p>If you have questions regarding my tutorial which is entitled as “<strong>INSERT AND DISPLAY DATA IN PHP &amp; MYSQL WITHOUT REFRESHING PAGE</strong>” feel free to ask us by commenting below or by visiting on our contact page. Thank you for supporting me and ITSOURCECODE.COM.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

Modern Approach: Using the fetch() API Instead of jQuery

If your project does not already use jQuery, the native fetch() API is the modern way to do AJAX without any library. Less code, no dependency:

// HTML form (no full submit reload)
<form id="studentForm">
  <input type="text" name="first_name" required>
  <input type="text" name="last_name" required>
  <button type="submit">Save</button>
</form>
<div id="result"></div>

<script>
document.getElementById("studentForm").addEventListener("submit", async (e) => {
    e.preventDefault();

    const formData = new FormData(e.target);
    const response = await fetch("save.php", {
        method: "POST",
        body: formData
    });
    const text = await response.text();
    document.getElementById("result").textContent = text;
    e.target.reset();   // clear form after submit
    loadStudents();     // refresh the list
});

async function loadStudents() {
    const r = await fetch("list.php");
    document.getElementById("list").innerHTML = await r.text();
}

loadStudents();   // initial load
</script>

Notice three things. First, e.preventDefault() stops the default form submission (which would reload the page). Second, FormData automatically picks up all named inputs. Third, the response is plain text we just drop into a div — PHP renders the row HTML on the server.

The PHP save.php Endpoint (Secure Version)

<?php
// save.php
header('Content-Type: text/plain; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method not allowed');
}

$first = trim($_POST['first_name'] ?? '');
$last  = trim($_POST['last_name'] ?? '');

if ($first === '' || $last === '') {
    http_response_code(400);
    exit('Both names are required');
}

$pdo = new PDO("mysql:host=localhost;dbname=school;charset=utf8mb4",
               "root", "",
               [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$stmt = $pdo->prepare("INSERT INTO students (first_name, last_name) VALUES (?, ?)");
$stmt->execute([$first, $last]);

echo "Saved!";
?>

Prepared statements with PDO prevent SQL injection. The http_response_code() calls give the client useful HTTP status codes so the JavaScript can detect failures.

Handling Errors on the Client Side

try {
    const response = await fetch("save.php", { method: "POST", body: formData });

    if (!response.ok) {
        const msg = await response.text();
        throw new Error(msg);
    }

    const text = await response.text();
    document.getElementById("result").textContent = text;
    loadStudents();
} catch (err) {
    document.getElementById("result").textContent = "Error: " + err.message;
}

fetch() only rejects on network errors, not HTTP 4xx/5xx. Always check response.ok manually if you want to handle server errors gracefully.

Common Mistakes With AJAX Insert/Display

  • Forgetting e.preventDefault(). The form submits normally and the page reloads, defeating the whole point of AJAX.
  • SQL injection from raw $_POST values. Always use prepared statements with PDO or MySQLi. Never concatenate user input into SQL strings.
  • XSS in displayed data. If you echo user input directly back to the page, an attacker can inject script tags. Use htmlspecialchars($value, ENT_QUOTES, 'UTF-8') on the PHP side.
  • Not validating on the server. Frontend validation can be bypassed by anyone with browser dev tools. Repeat all checks in PHP.
  • Returning sensitive data in error messages. Database error strings reveal schema. Log full errors with error_log(), return generic messages to users.
  • No CSRF token. An attacker on another site can submit a form to your endpoint if the user is logged in. Generate a token in the session and include it in every state-changing form.

Frequently Asked Questions

How do I insert data into a MySQL database without refreshing the page using PHP?

Use AJAX. The pattern: the form’s submit event is intercepted with e.preventDefault(), the form data is sent to a PHP endpoint via the fetch() API (or jQuery’s $.ajax), the PHP script inserts the data and returns a confirmation, and JavaScript updates the page with the new record — all without a page reload.

Should I use jQuery $.ajax or fetch() for AJAX in 2026?

For new projects, use fetch() — it’s a native browser API and works in all modern browsers without any library. jQuery’s $.ajax is still fine if your project already uses jQuery, but adding jQuery just for AJAX is overkill in 2026. The fetch() API does everything $.ajax does with less code.

How do I prevent SQL injection in PHP AJAX endpoints?

Use prepared statements. With PDO: $stmt = $pdo->prepare("INSERT INTO students (name) VALUES (?)"); $stmt->execute([$_POST['name']]);. The user input is bound as a parameter, never concatenated into the SQL. This works even if the user enters malicious SQL like '); DROP TABLE students;-- — it’s treated as literal text.

How do I display the inserted data immediately after AJAX submit?

Two common approaches. First, after the insert succeeds, call a second function (loadStudents()) that fetches the full list and replaces the table HTML. Second, on the server return the new row’s HTML and prepend it to the table on the client. The first approach is simpler; the second is faster because you only transfer one row.

What is the difference between fetch() and XMLHttpRequest?

XMLHttpRequest (XHR) is the older API from 1999, still used by jQuery’s $.ajax internally. fetch() is the modern Promise-based replacement. fetch() has cleaner syntax with async/await, better Promise handling, and is the API you should use for new code. XHR is only relevant when you need streaming progress events that fetch() does not support in older browsers.

Related PHP Tutorials

1 thought on “Insert and Display Data in PHP & MYSQL Without Refreshening Page”

Leave a Comment