LEARNING PHP: From Beginners to Advanced by DVZ Editorial

LEARNING PHP: From Beginners to Advanced by DVZ Editorial

Author:DVZ, Editorial
Language: eng
Format: epub
Published: 2023-12-03T00:00:00+00:00


PHP and AJAX - Updating Web Pages without Reloading

The no-reload web page refresh technique, commonly known as AJAX (Asynchronous JavaScript and XML), allows you to improve the user experience by loading or sending data to the server in the background without having to reload the entire page. In this chapter,we will explore how to integrate AJAX with PHP to achieve dynamic updates.

Introduction to AJAX:

AJAX uses JavaScript to make asynchronous requests to the server and manipulate the response without reloading the entire page. Let's create a simple example to understand how it works.

Practical example:

File Structure:

/project-ajax

├── index.php

├── update.php

└── script.js

index.php:

<!DOCTYPE html>

<html lang="es">

<head>

<meta charset="UTF-8">

<title>AJAX Update</title>

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

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

</head>

<body>

<h1>Counter: <span id="counter">0</span></h1>

<button onclick="incrementCounter()">Increment</button>

</body>

</html>

script.js:

function incrementCounter() {

// Make an AJAX request to the server

$.ajax({

type: "POST",

url: "update.php",

success: function(response) {

// Update the counter on the page

$("#counter").text(response);

}

});

}

update.php:

<?php

// Simulate a process on the server (you can perform more complex operations here)

// In this example, we simply increment a counter on the server.

session_start();

if (!isset($_SESSION['contador'])) {

$_SESSION['contador'] = 0;

}

$_SESSION['contador']++;

// Return the new counter value

echo $_SESSION['counter'];

Practical exercise:

Implements additional functionality in update.php to reset the counter to zero when a specific request is sent from the client. Modify the functionincrementCounter() in script.js to call this new functionality.

// In update.php

if (isset($_POST['reset'])) {

$_SESSION['contador'] = 0;

echo $_SESSION['counter'];

exit;

}

// And script.js

function resetCounter() {

$.ajax({

type: "POST",

url: "update.php",

data: { reset: true },

success: function(response) {

$("#counter").text(response);

}

});

}

Add a new button in index.php that calls the functionresetCounter(). This exercise will help you understand how to handle different actions with AJAX and PHP to dynamically update the web page without recharge it for complete.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.