Dublin, Ireland

All Content Copyright ©2019

WordPress Responseless XHR Request Using JavaScript

A responseless XHR (POST) request is a request which does not require any user feedback, such as storing post views or saving data in the background. Here’s how to achieve this in WordPress using JavaScript.

Add the PHP AJAX helper function:

 * Increment post views
 * Increments post views via AJAX.
 * @return null
function example_view_increment() {
    $postId = (int) $_POST['postId'];

    $viewsCount = get_post_meta($postId, '_view_count', true);

    update_post_meta($postId, '_view_count', $viewsCount);

add_action('wp_ajax_example_view_increment', 'example_view_increment');
add_action('wp_ajax_nopriv_example_view_increment', 'example_view_increment');

Here I have created a reusable XHR wrapper for a one line usage:

 * XHR API wrapper
 * A wrapper for XHR API
 * Usage:
 * apiPostXhr(myAjaxVar.ajaxurl, 'example_view_increment', '&postId=' + postId)
 * @param url string
 * @param data string
function apiPostXhr(url, action, data) {
    let request = new XMLHttpRequest();'POST', url, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.onload = function () {
        if (this.status >= 200 && this.status < 400) {
            // Response success
        } else {
            // Response error
    request.onerror = function() {
        // Connection error
    request.send('action=' + action + data);

Modify your template to get the post ID from a data parameter, such as <div class="single-post" data-pid="75">.

And here’s how to check if the element exists and call the function:

// Increment property views
if (document.querySelector('.single-post')) {
    // Get the post ID from a data parameter (depends on your structure)
    let postId = document.querySelector('.single-post');

    apiPostXhr(myAjaxVar.ajaxurl, 'example_view_increment', '&postId=' + postId);

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Wednesday, August 28, 2019 in JavaScript

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

Related Articles

My Battle Tested Recommendations
Disclaimer: These recommendations contain affiliate links.


Privacy Policy