0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Building a Secure AJAX Request System in PHP and JavaScript

0
Posted at

Modern web applications rarely reload an entire page when users submit data. Instead, they use AJAX (Asynchronous JavaScript and XML) to communicate with the server in the background, resulting in a much smoother user experience.

In this article, we'll build a simple AJAX workflow using JavaScript and PHP while following several security best practices.

Why AJAX?

Traditional forms refresh the entire page after submission.

AJAX allows applications to:

  • Send data without reloading the page
  • Display loading indicators
  • Handle errors gracefully
  • Build faster and more interactive applications

This pattern is widely used in search tools, dashboards, WordPress plugins, and SaaS products.


Project Structure

project/
│
├── index.php
├── ajax.php
├── script.js
└── style.css

Step 1: HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX Demo</title>
<link rel="stylesheet" href="style.css">
</head>

<body>

<div class="container">

<h2>AJAX Request Example</h2>

<input
type="text"
id="username"
placeholder="Enter username">

<button id="submitBtn">
Submit
</button>

<div id="result"></div>

</div>

<script src="script.js"></script>

</body>
</html>

Step 2: JavaScript

document
.getElementById("submitBtn")
.addEventListener("click", sendRequest);

function sendRequest(){

const username =
document.getElementById("username").value.trim();

if(username===""){
alert("Please enter a username.");
return;
}

document.getElementById("result").innerHTML="Loading...";

fetch("ajax.php",{

method:"POST",

headers:{
"Content-Type":"application/json"
},

body:JSON.stringify({

username:username

})

})

.then(response=>response.json())

.then(data=>{

document.getElementById("result").innerHTML=data.message;

})

.catch(()=>{

document.getElementById("result").innerHTML=
"Request failed.";

});

}

Step 3: PHP Backend

<?php

header("Content-Type: application/json");

$data=json_decode(file_get_contents("php://input"),true);

$username=trim($data["username"] ?? "");

if(empty($username)){

echo json_encode([
"message"=>"Username required."
]);

exit;

}

$username=htmlspecialchars(
$username,
ENT_QUOTES,
"UTF-8"
);

echo json_encode([
"message"=>"Hello ".$username
]);

Input Validation

Never trust user input.

Always validate:

  • Empty values
  • Maximum length
  • Invalid characters
  • SQL Injection attempts
  • Cross-Site Scripting (XSS)

Example:

if(strlen($username)>50){

exit("Too long");

}

Error Handling

Instead of exposing PHP warnings, return structured JSON.

echo json_encode([
"success"=>false,
"message"=>"Invalid request."
]);

This makes it easier for JavaScript to display user-friendly messages.


Security Tips

A production application should also include:

  • CSRF protection
  • Rate limiting
  • HTTPS
  • Server-side validation
  • Logging
  • Authentication when required

These measures help protect your application from common attacks.


Improving User Experience

Small interface improvements can make a significant difference:

  • Disable the button while loading.
  • Show a spinner during requests.
  • Display success and error messages clearly.
  • Prevent duplicate submissions.

These enhancements make applications feel faster and more reliable.


Where This Pattern Can Be Used

The same AJAX workflow can power many types of web applications, including:

  • Username availability checks
  • Search interfaces
  • Contact forms
  • Admin dashboards
  • WordPress AJAX handlers
  • Public content lookup tools

Because the communication logic is separated from the interface, the pattern is easy to reuse across projects.


Project Reference

The AJAX architecture shown in this article is based on patterns I use while developing personal web applications. One example project where this approach is applied is:

The link is provided only as a project reference for readers who want to see a complete implementation of a similar workflow.


Conclusion

AJAX is one of the most valuable techniques in modern web development. By combining JavaScript's Fetch API with a secure PHP backend, you can build responsive applications while keeping your code organised and maintainable.

As your projects grow, consider adding authentication, caching, logging, and rate limiting to create production-ready applications.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?