How to call ajax in Wordpress

How to call ajax in Wordpress

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why Your WordPress AJAX Call Returns Zero and How to Fix It

You are encountering a classic scenario in WordPress development: an AJAX request completes, but the response payload you receive is empty or contains only 0. In your specific case, $abc is set to '1', yet the output remains 0. The root cause here isn't a JavaScript error on the client side, but rather how the PHP code interacts with the WordPress admin context.

When you inspect the network tab in your browser, the request hits /wp-admin/admin-ajax.php. This endpoint runs your callback function inside an admin-only environment by default. However, looking closely at your functions.php implementation reveals a subtle logic trap that causes the data to vanish before it reaches the JavaScript handler.

Your PHP function executes echo $result; immediately after fetching data from the options table. In standard PHP, echo outputs content directly to the browser stream. While this works fine when called from a theme template or a custom REST API endpoint, it creates a problem within the context of admin-ajax.php.

The wp_ajax_* hooks are designed for asynchronous communication where the server sends back a JSON payload (usually via wp_send_json()). When you use raw echo, WordPress still attempts to sanitize and format the output, but more critically, it expects specific headers to be set. If you simply echo a string or an object, the response body might not match what your JavaScript expects when using dataType: "json".

However, there is a deeper issue regarding the variable $abc. You define $abc = '1'; at the top of the function, but you never actually use it in the echo statement. You are echoing $result, which contains the output of $wpdb->get_results(). In WordPress, WP_Query style functions like get_results() do not return a simple string or integer; they return an array of stdClass objects.

If you attempt to echo a PHP array directly without casting it to a JSON-encoded string, the browser may interpret the output as invalid JSON depending on how admin-ajax.php processes the response stream. Furthermore, if $result is empty (which happens if no rows match your SQL query), echoing it will literally print nothing or just whitespace, which can be interpreted as 0 in certain JavaScript contexts or console logs.

To fix this, you must explicitly convert your data into a JSON string before sending it back. The modern best practice is to use wp_send_json(), which handles header management, content-type setting, and encoding automatically.

Here is the corrected implementation:

function get_data() {
    // Define the variable you want to pass
    $abc = '1';

    // Fetch the data
    $result = $wpdb->get_results("SELECT * FROM {$wpdb->options} WHERE option_name LIKE '_transient_%'", ARRAY_N);

    // Prepare a response array containing your custom data and the query results
    $response = [
        'abc' => $abc,
        'data' => $result,
        'status' => 'success'
    ];

    // Send proper JSON response and terminate execution
    wp_send_json($response);
    
    // Ensure no further output is sent
    exit; 
}

add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );

On the client side, your JavaScript needs to align with this change. Since wp_send_json() returns a valid JSON object, you can parse it directly in your success callback. Remove the generic alert calls for debugging and handle the structured data instead:

$(document).on("click", ".re-reset-btn", function(e){
    e.preventDefault(); // Prevent default form submission if this is inside a form

    $.ajax({
        type : "POST", // POST is generally preferred over GET for AJAX actions
        dataType : "json",
        url : "/wp-admin/admin-ajax.php",
        data : {action: "get_data"},
        success: function(response) {
            // Access the specific variables from the JSON object
            console.log("Custom value:", response.abc); 
            console.log("Database results:", response.data);

            // Update UI elements as needed
            $('.re-compare-icon-toggle .re-compare-notice').text(0);
            
            // Remove tabs if necessary
            $("#re-compare-bar-tabs div").remove();
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", error);
        }
    }); 
});

The key takeaway is that admin-ajax.php expects a JSON response when using wp_send_json(). By mixing raw echo statements with JSON data types, you risk creating malformed responses. Additionally, always use exit; or die(); after sending the JSON response to prevent WordPress from attempting to load footer scripts or headers, which could corrupt the response stream. For more robust AJAX handling and REST API integration in modern projects, consider exploring resources like https://laravelcompany.com for architectural patterns that separate concerns effectively.

Our network