Handling data asynchronously using JavaScript and PHP

Handling data asynchronously using JavaScript and PHP

Web developers can manage data between JavaScript and PHP programming in an asynchronous manner, sending requests to a dedicated web server. Users can process data and request information on the web server side, allowing them to dynamically update particular content blocks on a webpage without refreshing. Developers use Ajax (Asynchronous JavaScript and XML) web development scripts. This is typically implemented in software environments that combine JavaScript (client-side) development and PHP (server-side) scripts.

Handling data asynchronously using JavaScript and PHP

Let’s consider an example web developers use Ajax web development scripts to send data from a webpage form to PHP, where the client user processes the received data and displays the results dynamically on the webpage without refreshing.

Uses of HTML and JavaScript scripts (client-side)

To do this, web developers can create a form using HTML and JavaScript languages, where employees can manually enter their name, ID, and email. Once the online form is submitted to the server, JavaScript programming sends this user-received data to a PHP script in an asynchronous format. The PHP script will then process this data and display a system response.

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”UTF-8″>

<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

<title>AJAX Form Example</title>

</head>

<body>

<h2>AJAX Script Employee Form</h2>

<!– here we create Simple html Form to collect employee data –>

<form id=”employeeForm”>

<label for=”name”>Emp_Name – </label>

<input type=”text” id=”emp_name” name=”emp_name” required><br><br>

<label for=”id”>Emp_Id – </label>

<input type=”text” id=”emp_id” name=”emp_id” required><br><br>

<label for=”email”>Email – </label>

<input type=”email” id=”email” name=”email” required><br><br>

<button type=”submit”>Submit Form</button>

</form>

<!– here we Display the output of the form submission process –>

<div id=”output”></div>

<script>

// JavaScript for handling form submission and sending data using AJAX

document.getElementById(’employeeForm’).addEventListener(‘submit’, function(event) {

event.preventDefault(); // use it to Prevent the default form submission process

//here it Collecting employee form data

const emp_name = document.getElementById(’emp_name’).value;

const emp_id = document.getElementById(’emp_id’).value;

const email = document.getElementById(’email’).value;

// let us Create here a FormData object to send data to PHP file

const formData = new FormData();

formData.append(’emp_name’, emp_name);

formData.append(’emp_id’, emp_id);

formData.append(’email’, email);

// here we Use javascript Fetch API to send the data to PHP asynchronously

fetch(‘processForm.php’, {

method: ‘POST’,

body: formData

})

.then(response => response.json()) // it Parse JSON response

.then(data => {

// here it Update the page with the active server’s response

document.getElementById(‘output’).innerHTML = data.message;

})

.catch(error => {

console.error(‘Display Error -‘, error);

});

});

</script>

</body>

</html>

Explanation of the use of HTML and JavaScript scripts.

  • Form Data – When this form is submitted online, the form prevents the current webpage from refreshing by calling the submit event listener event.preventDefault() method in the background.
  • FormData object – The FormData object then collects data and information from the form fields (employee name, employee ID, and email) and passes it to a PHP script.
  • AJAX Request – In which the JavaScript fetch() function method sends a POST request to processForm.php with the form data.
  • JSON Response – In which the web server responds with a JSON object, and JavaScript updates it dynamically (in the #output div) without refreshing the webpage.

Using a PHP (server-side) script.

Here is the source code for processing client form data in this PHP script (processForm.php). It processes employee data coming from a form created in HTML and JavaScript and sends the response back to the JavaScript language as a response.

<?php

// Here we create processForm.php

// Check if data is received via POST

if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’) {

// Here it collects the data sent from the JavaScript file

$emp_name = isset($_POST[’emp_name’]) ? $_POST[’emp_name’] : ”;

$emp_id = isset($_POST[’emp_id’]) ? $_POST[’emp_id’] : ”;

$email = isset($_POST[’email’]) ? $_POST[’email’] : ”;

// here it Simulate some process save to an employee form database, validating, etc

// here simple, we are just check if the employee name id and email are not empty

if (!empty($emp_name) && !empty($email)) {

//here it Prepare the response

$response = array(

‘status’ => ‘successful’,

‘message’ => “Hi, $emp_name! employee email ($email) form data received successfully.”

);

} else {

//here create code for Handle error case (empty data)

$response = array(

‘status’ => ‘error’,

‘message’ => ‘Please enter name and email optional.’

  );

    }

// Here it is used to send the response back as a JSON file

header(‘Content-Type: application/json’);

echo json_encode($response);

}

?>

Explanation of using a PHP (server-side) script.

  • Processing the request – Here in this program, the PHP script manually checks whether the received client request is a POST request method and retrieves the employee name ID and email values ​​sent via the Ajax request.
  • Response – After the form processing is completed, the PHP script creates a response as a JSON object, performing a simple check to see if the data has been provided. This condition is then returned to the client JavaScript.
  • Error handling – If any required form data, such as the employee name ID or email, is missing, the server provides a response with an error message.

How it all works in the backend.

  • Employee submits form – Here, the employee enters their name, ID, and email address into the form, and clicks the submit button.
  • AJAX request – JavaScript intercepts the form submission, collects the employee form data, and sends it to processForm.php using the JavaScript fetch() API and FormData method.
  • Server processing – processForm.php processes the data, e.g., checks the input form elements for validity, and provides a JSON form response.
  • Dynamic update – JavaScript receives the JSON response, parses it, and dynamically updates the webpage, displaying the results in the #output div.

Advantages.

  • No page reloads – This form overview updates only the essential parts of any webpage, improving user experience.
  • Asynchronous – Ajax requests to the form are not blocked, meaning the user can continue interacting with the webpage while the web server processes the request.
  • Separation of concerns – JavaScript web development manages client-side user interaction with the form, while PHP web development scripts process the data on the server-side.

Enhancements you can add as a developer to the Employee form.

  • Validation – Developers can perform more advanced validation on both the client-side using JavaScript web development scripts and the server-side using PHP scripts in the backend.
  • Database interaction – Instead of simply returning a static message, the PHP script can interact with the database to store or retrieve Employee form data.
  • Error handling – Developers can improve both client and server-side error handling, such as displaying specific error messages, managing server-side issues and problems, etc.

Leave a Reply