jQuery Ajax is the powerful tool of jQuery, You can create an attractive webpage with the help of JQuery ajax example. jQuery's Ajax methods return a superset of the XMLHttpRequest object.
This jQuery AJAX POST PHP example separates the browser request from the server action. The page sends named values in the background, PHP validates them, and the response is shown without replacing the current document.
How jQuery AJAX POST PHP works
Client, endpoint, and response
The client-side script chooses an endpoint and sends data with the POST method. The PHP file reads $_POST, checks the values, performs an operation, and returns a response. JavaScript then updates a message, table, or form area.
AJAX still uses HTTP; it simply avoids a full page navigation. Use GET when you are retrieving a resource and a URL with query parameters is useful. Use POST for submissions and operations that change server-side data.
- Keep field names consistent between HTML, jQuery, and PHP.
- Validate every value on the server, even when the browser uses
required. - Return a predictable response so the success and error callbacks can act correctly.
There are two commonly used methods for a request between a client and server: GET and POST.
Choose the right request data format
Serialize ordinary form fields
For text, email, select, and checkbox fields, serialized form data is usually enough. It produces key-value pairs that PHP can read through $_POST. Confirm that every control has a name attribute; an input with only an id is not included by the serializer.
Use FormData for uploads
When the form contains a file, create a FormData object instead of relying on serialize(). Set processData: false so jQuery does not convert the object, and set contentType: false so the browser can provide the multipart boundary.
const data = new FormData(document.getElementById('profile-form'));
$.ajax({
type: 'POST',
url: 'server_ajax.php',
data: data,
processData: false,
contentType: false,
success: function (response) {
$('#result').text(response.message || 'Uploaded.');
}
});
Return useful HTTP statuses
Use a success status when the operation completes, a client-error status such as 422 for invalid fields, and a server-error status when the application cannot finish the operation. This gives the browser and monitoring tools more information than a generic text response.
Do not expose SQL statements, file paths, stack traces, or database details in an AJAX response. Log diagnostic information on the server and show the visitor a short message that explains the next safe action.
GET - Requests data from a specified resource, basically used for just retrieving some data from the server.
POST - Submits data to be processed to a specified resource, used for setting some data to the server and also can retrieving tha data. POST method never caches data.
Download Now Laravel Project with Admin Dashboard
Ajax request is just like a web page call. Only difference is that the user doesn’t have to reload the page and user operation will be performed. Before you call a Ajax request you need to set JQuery link in your page, You can also download it.
Prepare a form for the request
A form is easier to maintain than hard-coding every value in the AJAX object. The name attributes become the keys that PHP receives, while a result element gives visitors feedback.
<form id="profile-form">
<input name="firstname" required>
<input name="lastname" required>
<input type="email" name="email" required>
<button type="submit">Save</button>
</form>
<div id="result" role="status"></div>
Bind to the submit event and call preventDefault() so the browser does not navigate away. For ordinary text fields, $(form).serialize() is a compact way to create the request data.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
Let’s get start with a basic JQuery Ajax POST request:
Send form data with jQuery
Use a success and error path
A useful request handles more than the successful response. Disable the button while the request is active, show a short loading message, and restore the button in complete so a slow connection does not create duplicate submissions.
Also decide how the interface should behave after success. Clear the form only when the server confirms the operation, preserve entered values when validation fails, and move focus to the result message when an important error needs attention. These details make an asynchronous form easier to understand for keyboard and assistive-technology users.
For larger responses, return structured fields such as an error list, a record identifier, or a redirect URL rather than embedding untrusted HTML in the response. Let the page create its own safe markup.
$("#profile-form").on("submit", function (event) {
event.preventDefault();
const form = this;
const result = $("#result");
const button = $(form).find("button");
$.ajax({
type: "POST",
url: "server_ajax.php",
data: $(form).serialize(),
dataType: "json",
beforeSend: function () {
button.prop("disabled", true);
result.text("Saving...");
},
success: function (response) {
result.text(response.message || "Saved.");
},
error: function (xhr) {
result.text(xhr.responseJSON?.message || "The request failed.");
},
complete: function () {
button.prop("disabled", false);
}
});
});
$.ajax({
type: "POST",
url: 'server.php',
success: function(data){
alert(data);
},
error: function (Status, errorThrown) {
}
});
Dofollow and nofollow links in seo
Now create an Ajax page on your project where you can place your MySQL code with PHP script. You can set your file name like server_ajax.php
<?php
require_once('config.php');
if(isset($_POST['firstname']) && isset($_POST['lastname']) && && isset($_POST['email']) ){
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$sql = "INSERT INTO my_ajax (firstname, lastname, email)
VALUES ($firstname, $lastname, $email)";
if (mysqli_query($conn, $sql)) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
else{
echo "Something went wrong";
}
mysqli_close($conn);
?>
JQuery ajax post example
Finally create your index page to call server_ajax.php:
Save data safely and debug failures
Use prepared database statements
Do not concatenate POST values into an SQL statement. Use a prepared MySQLi or PDO statement, keep credentials outside public source files, and give the database account only the permissions it needs.
$stmt = $connection->prepare(
'INSERT INTO my_ajax (firstname, lastname, email) VALUES (?, ?, ?)'
);
$stmt->bind_param('sss', $firstname, $lastname, $email);
$stmt->execute();
Inspect the Network panel
When the callback does not behave as expected, inspect the browser Network panel. Confirm the URL, method, submitted field names, status code, and response body. A 404 usually indicates a wrong path, a 422 indicates invalid input, and a 500 requires a server-side investigation.
- Use prepared statements to reduce SQL injection risk.
- Apply authentication, authorization, and CSRF protection to state-changing actions.
- Escape response values before placing them into HTML.
- Use FormData with
processData: falseandcontentType: falsewhen uploading files.
FAQ
How does PHP receive a jQuery POST request?
Ordinary form values are available through $_POST. JSON requests require reading and decoding the raw request body.
Why is the AJAX error callback running?
Check the endpoint path, HTTP status, PHP logs, and response format. Invalid JSON can also prevent a JSON success response from being parsed.
Is jQuery AJAX secure by itself?
No. The PHP endpoint must still validate input, authorize the action, protect against CSRF where needed, and use safe database queries.
Conclusion
A reliable jQuery AJAX POST PHP flow has a clear request, defensive server validation, a predictable response, and useful feedback for the visitor. Test both success and failure paths before connecting the endpoint to production data.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JQuery Ajax POST Example</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: 'server_ajax.php',
data: {firstname: 'Tony', lastname: 'stark', email: '[email protected]'},
success: function(data){
$("#result").append(data);
}
});
});
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>




Write a comment