Ajax POST request with jQuery and PHP
Today we will explain to you how to make ajax POST request with JQuery and PHP. In this article we’ll simply create form in HTML and submit form data via ajax POST request. Later on you can insert it into the database or use it in your further logic.
jQuery AJAX Post Example with PHP and JSON, jQuery Ajax POST example with PHP, How to POST data to php file using AJAX, How do I pass data to a php file using jquery AJAX, jQuery Ajax Post with data, Php jquery ajax post request example, Jquery Ajax Post Example For Submitting AJAX Forms in PHP, jQuery Ajax GET and POST Requests, Simple Ajax request example with JQuery and PHP, How to Use AJAX in PHP and jQuery, ajax post to php and get return data, send response from php to ajax, how to use ajax response in php, jquery ajax call php function with parameters, ajax pass variable to php, how to get ajax value in php
Checkout more articles on PHP
- Convert base64 to image file in PHP
- Delete all files from a folder in PHP
- How to generate random password using PHP and MySQL
- Convert CSV to JSON in PHP
- Replace image src in HTML using PHP
What is AJAX and how it works
AJAX stands for Asynchronous JavaScript and XML, is a client-side script that allows web applications to work asynchronously without a page refresh. It fetches the data from the back-end server and updates the part of the web page without reloading the whole webpage.
Basic Ajax POST request
$.ajax({
type: "POST",
url: 'script.php',
data: {name: 'John'},
success: function(data){
console.log(data);
},
error: function(xhr, status, error){
console.error(xhr);
}
});
Let’s try to understand the parameters in brief.
- type - Type of http request like POST, GET, PUT, DELETE. In the above code snippets, we used POST.
- url - The external URL that we want to send the ajax request. Here we used `script.php`.
- data - Data which we want to send in the request. We have passed `{name: ‘John’}` in the above code.
- success - If the ajax request runs successfully then this function is called. In the above function we have a data parameter that is the output of the request url.
- error - If the ajax request failed then this function is called so we can debug the issue.
Also, we can use a `datatype` parameter i.e. json that helps us to receive the data in expected format from the server.
It’s time to create an example so I would like to divide this article in separate steps. In this example we’ll create an HTML form that contains the fields such as name, email and message and handle ajax POST request on click of the submit button.
Steps to make Ajax POST request with JQuery and PHP
- Create an HTML form
- Include the jQuery library
- Write a script for ajax call
- Handle POST data in PHP file
- Output
1. Create an HTML form
In the first step, we have to create an HTML form with the use of several fields like First Name, Last Name, Email and Message. Also we’ll add the button to submit the form data via ajax call.
Check the below code where we have created only HTML form.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax POST request with JQuery and PHP</title>
<style type="text/css">
body {
font-family: calibri;
}
.box {
margin-bottom: 10px;
}
.box label {
display: inline-block;
width: 80px;
text-align: right;
margin-right: 10px;
}
.box input, .box textarea {
border-radius: 3px;
border: 1px solid #ddd;
padding: 5px 10px;
}
.btn-submit {
margin-left: 90px;
}
</style>
</head>
<body>
<h2>Ajax POST request with JQuery and PHP - <a href="https://www.cluemediator.com" target="_blank">Clue Mediator</a></h2>
<form>
<div class="box">
<label>First Name:</label><input type="text" name="firstName" id="firstName" />
</div>
<div class="box">
<label>Last Name:</label><input type="text" name="lastName" id="lastName" />
</div>
<div class="box">
<label>Email:</label><input type="email" name="email" id="email" />
</div>
<div class="box">
<label>Message:</label><textarea type="text" name="message" id="message"></textarea>
</div>
<input id="submit" type="button" class="btn-submit" value="Submit" />
</form>
</body>
</html>
Here we are not adding any validation because our goal is to provide the straight forward explanation of the article.
2. Include the jQuery library
We have to include the below jQuery library in the head section of the page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
3. Write a script for ajax call
Now in the next step, we have to write a script that helps us to place the ajax POST request on click of the submit button.
Following script will execute on click of the submit button.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var email = $("#email").val();
var message = $("#message").val();
if(firstName==''||lastName==''||email==''||message=='') {
alert("Please fill all fields.");
return false;
}
$.ajax({
type: "POST",
url: "submission.php",
data: {
firstName: firstName,
lastName: lastName,
email: email,
message: message
},
cache: false,
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
});
});
</script>
In the above code, we used `submission.php` file as request URL to handle the request in the backend and also we display the response via alert method.
Let’s combine the above code together and see how it looks.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax POST request with JQuery and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
body {
font-family: calibri;
}
.box {
margin-bottom: 10px;
}
.box label {
display: inline-block;
width: 80px;
text-align: right;
margin-right: 10px;
}
.box input, .box textarea {
border-radius: 3px;
border: 1px solid #ddd;
padding: 5px 10px;
}
.btn-submit {
margin-left: 90px;
}
</style>
</head>
<body>
<h2>Ajax POST request with JQuery and PHP - <a href="https://www.cluemediator.com" target="_blank">Clue Mediator</a></h2>
<form>
<div class="box">
<label>First Name:</label><input type="text" name="firstName" id="firstName" />
</div>
<div class="box">
<label>Last Name:</label><input type="text" name="lastName" id="lastName" />
</div>
<div class="box">
<label>Email:</label><input type="email" name="email" id="email" />
</div>
<div class="box">
<label>Message:</label><textarea type="text" name="message" id="message"></textarea>
</div>
<input id="submit" type="button" class="btn-submit" value="Submit" />
</form>
<script>
$(document).ready(function() {
$("#submit").click(function() {
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var email = $("#email").val();
var message = $("#message").val();
if(firstName==''||lastName==''||email==''||message=='') {
alert("Please fill all fields.");
return false;
}
$.ajax({
type: "POST",
url: "submission.php",
data: {
firstName: firstName,
lastName: lastName,
email: email,
message: message
},
cache: false,
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
});
});
</script>
</body>
</html>
4. Handle POST data in PHP file
Let’s create a php file as `submission.php` to manage the upcoming data from the HTML file and revert back in JSON format as response.
submission.php
<?php
/*
* Write your logic to manage the data
* like storing data in database
*/
// POST Data
$data['name'] = $_POST['firstName'] . " " . $_POST['lastName'];
$data['email'] = $_POST['email'];
$data['message'] = $_POST['message'];
echo json_encode($data);
exit;
?>
5. Output
Run the above code and check the output in the browser.
Output - Ajax POST request with JQuery and PHP - Clue Mediator
That’s it for today.
Thank you for reading. Happy Coding!