Serializing form data means converting the form's input values into a URL-encoded string. This allows us to send the data using AJAX to a PHP script for processing. Using serialized data simplifies sending multiple fields at once.
When a form is submitted, JavaScript collects all input values and converts them into a serialized string such as name=John&email=john@example.com. This string is then sent to a PHP script using AJAX where the server reads values from the $_POST array.
// HTML form with various input types
<form id="myForm">
<label>Name:</label>
<input type="text" name="name"><br><br>
<label>Email:</label>
<input type="text" name="email"><br><br>
<label>Gender:</label>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br><br>
<label>Hobbies:</label>
<input type="checkbox" name="hobbies[]" value="Reading"> Reading
<input type="checkbox" name="hobbies[]" value="Gaming"> Gaming<br><br>
<button type="submit">Submit</button>
</form>
<div id="response"></div>
// JavaScript AJAX request with serialized form data
document.getElementById('myForm').addEventListener('submit',function(e){
e.preventDefault();
const formData=new FormData(this);
const params=new URLSearchParams(formData).toString();
const xhr=new XMLHttpRequest();
xhr.open('POST','process.php',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onload=function(){
if(xhr.status===200){
document.getElementById('response').innerHTML=xhr.responseText;
}
};
xhr.send(params);
});
// PHP script to receive and process serialized form data
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$name=$_POST['name'] ?? '';
$email=$_POST['email'] ?? '';
$gender=$_POST['gender'] ?? '';
$hobbies=isset($_POST['hobbies'])?implode(', ',$_POST['hobbies']):'';
echo "Received: Name = $name, Email = $email, Gender = $gender, Hobbies = $hobbies";
}
?>
After submitting the form, the response from process.php is displayed instantly without page reload.
The form submission is handled entirely via JavaScript and AJAX, creating a smooth user experience without refreshing the page.