WordPress is consistently returning 0 when using ajax, however in certain instances it should be returning a value of

I have developed an AJAX function within WordPress for my plugin. In the plugin construct, I am setting up the AJAX callback:

public function __construct() {
    return $this->register();
}

/**
 * Register all new files in WooCommerce hooks
 */
public function register() {
    if ( is_user_logged_in() ) {
        add_action( 'wp_ajax_filter', array( $this, 'filter' ) );
    } else {
        add_action( 'wp_ajax_nopriv_filter', array( $this, 'filter' ) );
    }
}

Below is the jQuery function responsible for triggering the AJAX call:

jQuery(document).ready(function () {
    jQuery(document).on('click', '.filter-menu li', function () {
        var filter_value = jQuery(this).find('.menu-data-inner');

            var data = {
                'action': 'filter',
                'filter': filter_value.attr('data-value'),
                'filter_status': 1
            };      

            var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";

            jQuery.post(ajaxurl, data, function () {
                jQuery('#content-area').load(location.href + ' #content-area>*', '');
            });
        }
    });
});

After making the request, I refresh the main content of WordPress through AJAX and anticipate that my function in functions.php will be skipped because of DOING_AJAX.


This is the function that is called by the AJAX request:

/**
 * Filter
 */
public function filter() {
    require 'functions/filter.php';
    wp_die();
}

This is the content of the required file:

<?php error_log( $_POST['filter'] ); ?>

My issue now arises as I included this function in my functions.php:

add_action( 'init', 'do_something' );
function do_something() {
    error_log('INIT');
}

However, it quickly became apparent that this caused a problem because the init is also triggered during AJAX requests, which is not desired. It should only display INIT when the page is loaded by pressing F5 or entering the site URL and pressing enter. So I added a condition:

add_action( 'init', 'do_something' );
function do_something() {
    if ( ! wp_doing_ajax() ) {
        error_log('INIT')
    }
}

Even after calling the AJAX again, the debug log still shows INIT, but it shouldn't. Therefore, I attempted to modify the function that is called during AJAX like this:

<?php 
    error_log( $_POST['filter'] ); 

    define( 'DOING_AJAX', true ); ?>

Unfortunately, this did not solve the problem. The error_log persists.

So what could be the issue here? What am I doing wrong? I followed the documentation, but it seems like DOING_AJAX isn't functioning as expected for me.

Answer №1

you require

add_action( 'wp_ajax_filter', array( $this, 'filter' ) );

for each ajax request you make however,

add_action( 'wp_ajax_nopriv_filter', array( $this, 'filter' ) );

is needed when the user is not logged in so it should be changed to :

public function register() {
    if ( is_user_logged_in() ) {
        add_action( 'wp_ajax_filter', array( $this, 'filter' ) );
    } else {
        add_action( 'wp_ajax_filter', array( $this, 'filter' ) );
        add_action( 'wp_ajax_nopriv_filter', array( $this, 'filter' ) );
    }
}

this could explain why you are receiving 0 for your requests

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with JSON Stringify and parsing errors in AJAX

I've been troubleshooting this issue for hours, trying various suggestions found online, but I'm still encountering a problem. Whenever I encode function parameters using JSON.stringify and send them to my PHP handler through AJAX, I receive a pa ...

Tips for retrieving a many-to-many result in CakePHP

I am dealing with a many-to-many relationship between the Image and Units models by using an images_units join table. Looking for guidance on how to convert this query to a cakePHP find() method. SELECT * FROM Image, Units, images_units WHERE images_unit ...

Stop duplicate messages from appearing in AJAX chat feature (JavaScript, PHP, MySQL)

I developed a real-time chat system using AJAX, Javascript, PHP, and MySQL. Chat data is sent via JSON from a PHP page that retrieves information from a MySQL database. Each message is stored in an array and fetched through an AJAX call at regular interva ...

Storing chosen choices from various select lists with similar class name in JavaScript

I am struggling to save all the selected options in an array for future output. Despite trying various suggestions, I haven't been able to make it work yet. The class names and names cannot be modified. HTML <select class="addon addon-select" nam ...

Is there a way to display an asterisk within a select2 dropdown to signify that a field is mandatory?

I'm facing an issue with the Select2 plugin in my form. While all fields are required and marked by an asterisk when empty, the Select2 dropdown ignores this validation attribute. Therefore, I am wondering: Is there a way to display an asterisk image ...

Transforming the initial character of a label element into uppercase

When I receive an external HTML page, all the data comes in lowercase. I attempted to capitalize the first letter of each label tag using CSS, but it ended up making the entire text uppercase instead. Here is what I tried: .fontmodal { text-transform ...

How to access the calling scope within a PHP function?

Is it possible to access the scope of the calling environment from within a called function? For instance, how can I retrieve __LINE__ in a logging function but ensure it reflects the actual line number from the calling context? Additionally, is there a w ...

What is the best way to ensure jQuery loads before CSS code on a website

I am currently working on a blog project that allows visitors to customize the background color by simply clicking on one of five available buttons. $(function(){ //Checking if a color scheme has already been selected var chosenColor = ...

Combining various postponed JavaScript file imports in the HTML header into a single group

I've been facing an issue with my code structure, particularly with the duplication of header script imports in multiple places. Every time I need to add a new script, I find myself manually inserting <script type="text/javascript" src=&q ...

Refresh DataTable while making a fetch request

Here is the HTML code snippet where I want to apply DataTable: <div id="reportrange" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc;"> <span></span> </div> <table id=" ...

Utilizing ajax for a particular scenario within the Rails framework

I implemented a dropdown login form that redirects the user to the root path upon successful login, or updates the form with an error message if the login fails without refreshing the page. To achieve this, I utilized AJAX to display the error message. T ...

Implementing AJAX requests in jQuery DataTable with ASP.NET MVC

For some time now, I have been using the jQuery DataTables 1.10.13 plugin. Recently, I encountered an issue related to the ajax data source for my HTML table. This is how I initialized jQuery DataTable inside Files.cshtml <script language="javascript" ...

Troubleshooting Problems with Retrieving Data Using jQuery and

Having trouble fetching information from a JSON file, as the data variable is empty. I have already downloaded the JSON file, so it's not an issue with the server connection. Can anyone point out where I might be going wrong? function handle_geolocat ...

Tips for adding up information in a JSON array received from the controller and passed to the view in Laravel

I have encountered a problem with the JSON array provided below: $results = [ { proj_name: rental, act_name: income, amount: "1000" }, { proj_name: rental, act_name: expend, amount: "-2000" }, { proj_name: r ...

jquery accordion failing to display content

Upon navigating to my website and accessing the webpage featuring an accordion, the accordion successfully appears and hides after 1500ms as intended. However, when attempting to reveal the text by clicking on the headings, nothing happens. The heading sim ...

Creating a lively JQ plot and saving it within an HTML file from a .aspx page using C# .net

I am currently in the process of developing a web-based application using Bootstrap. My goal is to save a .aspx page as an HTML file within my application. Upon writing the code: using System; using System.Collections.Generic; using System.Linq; using S ...

Retrieve categories only from locations using Laravel Eloquent

I am looking to extract only the categories that are present in a specific town, such as clubs and bars. In my controller code, I have included the following snippet to retrieve the necessary data for the view: $town = Town::where('identifier&apo ...

"An issue of 405 error encountered while using AJAX for form

I'm currently working on implementing AJAX functionality for a form in my Django project. Despite being relatively new to web development, I understand that I need to make an AJAX call using POST to a specific URL, which I've set as /message/. Up ...

Employ a adjusted column or partitioned table within the database

I need to store the following information in a MySQL database for notifications: id: VARCHAR(10) from_id: VARCHAR(10) to_id: VARCHAR(10) type: int(2) type_info: (The issue lies within this column) date : TIMESTAMP The type_info column's content is d ...

Eliminate the /page/ portion from the URL upon accessing pages

We recently implemented a paging system on our website layout. By visiting /page/clan, users can access the clan page content (located in pages/clan.php). To achieve this, we utilized an htaccess script to rewrite index.php?page=pagename into the user-fri ...