AJAX - AJAX Integration with Web Push Notifications

 

1. Introduction

AJAX integration with Web Push Notifications is a technique used in web development to keep users informed about important updates even when they are not actively interacting with a website. AJAX allows a web application to exchange data with a server without reloading the entire web page, while Web Push Notifications enable a website to deliver notifications to users through a supported browser.

When these technologies are combined, a website can retrieve updated information in the background, display relevant changes within the page, and notify users about important events. For example, an online shopping website can use AJAX to retrieve the latest order status and Web Push Notifications to alert the customer when the order is shipped or delivered.

This integration is useful for applications that need to provide timely information, such as messaging platforms, e-commerce websites, online learning portals, news websites, and project management systems.

2. What Are AJAX and Web Push Notifications?

AJAX

AJAX stands for Asynchronous JavaScript and XML. Despite its name, modern AJAX applications commonly exchange data in JSON format rather than XML.

AJAX allows a web page to communicate with a server without refreshing the entire page. JavaScript sends a request, receives a response, and updates the relevant part of the page.

For example, when a student opens an online learning portal, AJAX can retrieve new assignment details and display them without reloading the page.

The main advantages of AJAX include:

  • Updating page content dynamically.

  • Reducing unnecessary full-page reloads.

  • Improving user experience and responsiveness.

  • Retrieving information from server-side applications asynchronously.

Web Push Notifications

Web Push Notifications are messages delivered through a browser's push notification system. They can inform users about events even when the website is not currently open in an active tab, provided the browser and operating system support the required features and the user has granted permission.

Web Push Notifications typically involve three important components:

  1. Service Worker: A JavaScript script that runs separately from the web page and can handle events such as incoming push messages.

  2. Push Service: A service that routes push messages from the application server to the user's browser.

  3. Notification API: A browser interface used to display notifications to the user.

For example, a news website can send a notification when an important news story is published. When the user clicks the notification, the browser can open the relevant article.

3. Why Integrate AJAX with Web Push Notifications?

AJAX and Web Push Notifications perform different but complementary functions. AJAX retrieves information when the application needs it, whereas push notifications alert users when important events occur.

Consider an online shopping application. A customer places an order and closes the website. Later, the order status changes from "Processing" to "Shipped."

If the website relies only on AJAX polling, the browser must periodically contact the server to check for changes, and the user may not see the update until the page is opened or another request is made.

With Web Push Notifications, the server can send a push message when the order status changes. The service worker can display a notification, and clicking it can open the order details page. Once the page is open, AJAX can retrieve the latest order information from the server.

This integration offers several benefits:

  • Timely updates: Users can receive notifications about important events.

  • Reduced unnecessary polling: Applications can avoid repeatedly checking for updates when event-driven notifications are sufficient.

  • Better user engagement: Notifications can encourage users to return to a website when relevant information becomes available.

  • Dynamic content: AJAX can update page elements without a full-page reload.

  • Improved continuity: Notifications can direct users to the precise page where further information is available.

Push notifications do not replace AJAX. Instead, they complement it by notifying users of an event and allowing the application to retrieve the latest information when needed.

4. How AJAX Integration with Web Push Notifications Works

The integration involves several steps, from obtaining user permission to retrieving updated information.

Step 1: User grants notification permission

The website asks whether the user wants to receive notifications.

 

Step 2: Browser registers a service worker

The service worker is installed and activated for the website.

 

Step 3: Browser creates a push subscription

The application obtains a subscription containing the push endpoint and encryption keys.

 

Step 4: Subscription is saved on the server

JavaScript sends the subscription details to the application server, often using AJAX.

 

Step 5: Server sends a push message

When an important event occurs, the server sends a message through the push service.

 

Step 6: Notification is displayed

The service worker receives the push event and displays a notification.

 

Step 7: User opens the notification

The browser opens the relevant page, where AJAX retrieves the latest data.

The process depends on browser support, user permission, a valid subscription, and a properly configured server. Push delivery is not guaranteed to be instantaneous.

5. Role of the Service Worker

A service worker is a JavaScript file that runs separately from the main web page. It can respond to certain browser events even when the website does not have an active page open.

In a push notification system, the service worker listens for incoming push events and displays notifications. It can also handle notification clicks and open the appropriate page.

A simplified service worker example is shown below.

self.addEventListener("push", (event) => {
    let data = {
        title: "Website Update",
        body: "New information is available.",
        url: "/updates"
    };

    if (event.data) {
        data = {
            ...data,
            ...event.data.json()
        };
    }

    event.waitUntil(
        self.registration.showNotification(data.title, {
            body: data.body,
            data: {
                url: data.url
            }
        })
    );
});

self.addEventListener("notificationclick", (event) => {
    event.notification.close();

    const url = event.notification.data?.url || "/updates";

    event.waitUntil(
        clients.openWindow(url)
    );
});

In this example, the service worker listens for a push event, extracts the notification details, and displays a notification. When the user clicks it, the browser opens the specified page.

The example assumes that the server sends valid JSON data. Production applications should validate incoming data, restrict notification destinations to trusted URLs, and handle malformed messages safely.

6. Using AJAX to Register a Push Subscription

Before a website can send push notifications to a user, the browser needs to create a push subscription. The application server must store that subscription so it knows where to send future messages.

The following example demonstrates how JavaScript can register a service worker, request notification permission, create a subscription, and send the subscription details to the server.

async function enablePushNotifications() {
    if (!("serviceWorker" in navigator) ||
        !("PushManager" in window)) {
        throw new Error("Push notifications are not supported.");
    }

    const permission = await Notification.requestPermission();

    if (permission !== "granted") {
        throw new Error("Notification permission was not granted.");
    }

    const registration = await navigator.serviceWorker.register(
        "/service-worker.js"
    );

    await navigator.serviceWorker.ready;

    const subscription = await registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: getVapidPublicKey()
    });

    const response = await fetch("/api/push-subscriptions", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(subscription)
    });

    if (!response.ok) {
        throw new Error("Unable to save the push subscription.");
    }

    return await response.json();
}

The getVapidPublicKey() function represents an application-specific function that returns the server's VAPID public key in the format expected by the browser. VAPID is a mechanism used to identify the application server to the push service.

The fetch() call is an AJAX request. It sends the subscription information to the application server without requiring a full-page reload.

The server should associate the subscription with the correct user, protect the endpoint against unauthorized requests, and store subscription information securely. Notification permission should normally be requested in response to a clear user action, such as clicking an "Enable notifications" button.

7. Retrieving Updated Information Through AJAX

Receiving a push notification does not always mean that the notification contains all the information the user needs. In many applications, the notification contains a short message and a reference to the relevant resource.

When the user opens the corresponding page, AJAX retrieves the current information from the server.

For example, an online learning portal may notify a student that a new assignment has been published. The assignment page can then request the latest details.

async function loadAssignments() {
    try {
        const response = await fetch("/api/assignments");

        if (!response.ok) {
            throw new Error("Unable to load assignments.");
        }

        const assignments = await response.json();
        const list = document.getElementById("assignmentList");

        list.replaceChildren();

        assignments.forEach((assignment) => {
            const item = document.createElement("li");
            item.textContent =
                `${assignment.title} - Due: ${assignment.dueDate}`;

            list.appendChild(item);
        });
    } catch (error) {
        console.error("Assignment loading failed:", error);
    }
}

This example retrieves assignment data and updates the relevant HTML list. The page does not need to reload completely.

Using textContent instead of inserting untrusted response values through innerHTML also helps reduce the risk of cross-site scripting when displaying text.

8. Practical Applications

E-commerce websites

Online stores can send push notifications about order confirmation, shipment progress, delivery status, and price changes. When users open the notification, AJAX can retrieve the current order or product details.

Online education platforms

Educational websites can notify students when new assignments, examination schedules, grades, or learning materials become available. AJAX can retrieve the latest course information when the student opens the relevant page.

Messaging applications

A messaging application can use push notifications to alert users about new messages. Once the conversation is opened, AJAX can retrieve message history and update the conversation interface.

News websites

News portals can send notifications about major events or breaking news. Clicking a notification can open the corresponding article, while AJAX retrieves the latest article data or related updates.

Project management systems

Business applications can notify team members about task assignments, approaching deadlines, approvals, and project changes. AJAX can refresh task lists and dashboards when users return to the application.

9. Security and Performance Considerations

Integrating AJAX with Web Push Notifications requires careful security and performance management.

User consent: Websites should clearly explain the value of notifications and request permission at an appropriate moment. Users must be able to manage or revoke their notification permission.

HTTPS requirements: Service workers and push notifications generally require a secure context, such as HTTPS, with localhost commonly supported for development.

Subscription protection: Push subscription endpoints and associated keys should be handled carefully. They should not be exposed unnecessarily or accepted from unauthorized users.

Server-side validation: The application server must validate requests, authenticate users where required, and prevent unauthorized users from registering or modifying subscriptions.

Data minimization: Notifications should avoid exposing sensitive information on lock screens or shared devices. A short message such as "Your order status has changed" may be safer than displaying personal or financial details.

Notification frequency: Sending too many notifications can frustrate users. Applications should prioritize important events, prevent duplicates, and provide notification preferences.

Subscription expiration: Push subscriptions can become invalid. The server should detect expired or rejected subscriptions and remove or update them appropriately.

Performance: AJAX requests should retrieve only the information needed by the page. Applications should avoid unnecessary requests, handle network failures, and use caching where appropriate.

Delivery limitations: Push notifications may be delayed, suppressed, or unavailable because of browser restrictions, device settings, connectivity, or operating system behavior. They should not be treated as a guaranteed real-time delivery mechanism.

10. Advantages and Limitations

Advantages

Limitations

Provides timely alerts about important events.

Requires user permission for notifications.

Allows pages to update without full reloads.

Depends on browser and platform support.

Can reduce the need for frequent polling.

Requires server-side push infrastructure.

Improves user engagement and accessibility of updates.

Notifications may be delayed or suppressed.

Works well with service workers and modern web applications.

Requires careful security and subscription management.

11. Conclusion

AJAX integration with Web Push Notifications combines dynamic data retrieval with event-driven user alerts. AJAX enables web pages to communicate with servers and update their content without refreshing the entire page, while Web Push Notifications allow websites to inform users about important events even when they are not actively viewing the website.

A typical implementation uses a service worker to receive push messages, a push service to deliver them, and an application server to manage subscriptions and send notifications. AJAX is then used to register subscriptions, retrieve updated information, and refresh the interface when required.

This approach is especially useful for e-commerce websites, educational platforms, messaging applications, news portals, and project management systems. When implemented with appropriate user consent, secure server-side validation, and sensible notification policies, it can make web applications more responsive, informative, and convenient to use.