Home > Backend Development > PHP Tutorial > How Does Long Polling Efficiently Update Web Applications Without Constant Page Refreshing?

How Does Long Polling Efficiently Update Web Applications Without Constant Page Refreshing?

Mary-Kate Olsen
Release: 2024-12-25 11:47:42
Original
839 people have browsed it

How Does Long Polling Efficiently Update Web Applications Without Constant Page Refreshing?

Understanding Long Polling: A Beginner's Guide

Long polling is a technique that allows web applications to efficiently wait for new data from the server without constantly refreshing the page. This is particularly useful for applications where data is updated infrequently, such as chat or social networking applications.

Implementing Basic Long Polling in PHP and JavaScript

While long polling can appear complex, its implementation can be surprisingly straightforward. Let's walk through a basic example using PHP and JavaScript:

PHP Script (msgsrv.php)

<?php
if (rand(1, 3) == 1) {
    header("HTTP/1.0 404 Not Found");
    die();
}

sleep(rand(2, 10));
echo("Hi! Have a random number: " . rand(1, 10));
?>
Copy after login

This script simulates a simple message server. It generates a random number and sends it as a response, with a random delay between 2 and 10 seconds to mimic real-world conditions.

JavaScript Code (long_poller.htm)

<html>
<head>
    <script src="jquery.min.js"></script>
    <script>
        function addmsg(type, msg) {
            $("#messages").append("<div class='msg " + type + "'>" + msg + "</div>");
        }

        function waitForMsg() {
            $.ajax({
                url: "msgsrv.php",
                success: function (data) {
                    addmsg("new", data);
                    setTimeout(waitForMsg, 1000);
                },
                error: function () {
                    addmsg("error", "Error");
                    setTimeout(waitForMsg, 15000);
                }
            });
        }

        $(document).ready(function () {
            waitForMsg();
        });
    </script>
</head>
<body>
    <div>
Copy after login

This JavaScript code uses jQuery to request the PHP script asynchronously. If the request is successful, it adds the response to the #messages div. If the request fails, it displays an error and tries again after 15 seconds. The setTimeout function ensures that the browser requests the script at a regular interval, thus implementing long polling.

Explanation

This example demonstrates a simplified implementation of long polling. The PHP script simulates a server that sends data at irregular intervals. The JavaScript code repeatedly requests the script using AJAX, waiting for a response. When a response is received, the JavaScript code updates the UI. If there is no response, the script waits for a short period and tries again. This approach allows the web application to remain responsive while efficiently waiting for server-side updates.

The above is the detailed content of How Does Long Polling Efficiently Update Web Applications Without Constant Page Refreshing?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template