1

I am new to working with AJAX. For whatever reason, every time I refresh the page, there doesn't seem to be any error, just an alert box with [object Object]. I do not understand why this occurs.

<script>
jQuery(document).ready(function($) {

    // This is the variable we are passing via AJAX
    var fruit = 'Banana';

    // This does the ajax request (The Call).
    $.ajax({
        url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
        data: {
            'action':'example_ajax_request', // This is our PHP function below
            'fruit' : fruit // This is the variable we are sending via AJAX
        },
        success:function(data) {
    // This outputs the result of the ajax request (The Callback)
            window.alert(data);
        },
        error: function(errorThrown){
            window.alert(errorThrown);
        }
    });

});
</script>
 
 
 <?php
 
    function example_ajax_request() {

    // The $_REQUEST contains all the data sent via AJAX from the Javascript call
    if ( isset($_REQUEST) ) {

        $fruit = $_REQUEST['fruit'];

        // Processes the fruit variable into an Apple
        if ( $fruit == 'Banana' ) {
            $fruit = 'Apple';
        }

        // Returns the result to the Javascript function (The Callback)
        echo $fruit;
    }

   die();
}


add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );

Edit: I tried console.log(data) and errorThrown and got an error message with: Failed to load resource: the server responded with a status of 400 ()

3
  • I'm not sure this is specific to WordPress, but JavaScript. You have 2 alerts in your script, data and errorThrown so one of those is an object. Try to use console.log instead of window.alert
    – Howdy_McGee
    Commented Apr 28, 2023 at 18:38
  • I consoled it out, and it returned an error stating: Failed to load resource: the server responded with a status of 400 ()
    – John Lyons
    Commented Apr 28, 2023 at 18:39
  • this looks like a jQuery question rather than a WordPress question, you should ask at stackoverflow
    – Tom J Nowell
    Commented Apr 28, 2023 at 18:44

2 Answers 2

1

These lines are responsible for the alert:

success: function(data) {
    window.alert(data);
},
error: function(errorThrown){
    window.alert(errorThrown);
}

In the first block, success, the callback function is executed if the ajax request succeded. The second block, error, will run if the request returned an error.

Right now in both cases an alert is triggered via window.alert() function call. You should replace these calls with your own logic.

To start, replace them with console.log() calls passing the data you're interested in. Then open your browser's console and check the data printed there.

If you see 400 error in the console with WordPress, check this answer:

https://stackoverflow.com/questions/48025825/wordpress-admin-ajax-php-400-bad-request/48026371#48026371.

3
  • I recently did and got a 400 error message. Could that mean that there is a syntactical issue?
    – John Lyons
    Commented Apr 28, 2023 at 18:43
  • @JohnLyons just updated the answer, see stackoverflow.com/questions/48025825/… Commented Apr 28, 2023 at 18:44
  • Bizzare. Now I have this strange 308 error: <b>Warning</b>: call_user_func_array() expects parameter 1 to be a valid callback, function 'example_ajax_request' not found or invalid function name in <b>/home/kvfgs3t3g18k/public_html/wp-includes/class-wp-hook.php</b> on line <b>308</b><br /> 0
    – John Lyons
    Commented Apr 28, 2023 at 20:11
0

The main problem with your Ajax call is that there are two options (locations) for these ajax calls in Wordpress (and usually in any CMS):

  1. Admin area calls.
  2. Front-end calls.

So if your Ajax call is from front-end thus anybody can use that request then you should use this version of adding an action in your functions.php file:

add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );

so 'wp_ajax_my_function' will not work on front-end usage. WP will not find your PHP callback function for the Ajax call.

The second I would like to bring your attention to is the important part of the Ajax call which is the target URL:

url: ajaxurl // always defined...

I have seen this at many places and it is a bit misleading people that ajaxurl is always defined since... version... It is only true for admin Ajax calls again. For front-end Ajax calls you should define the target url yourself. That is true that it is always targeting admin-ajax.php, but still we have to define that in our javascript for ourself.

The working sample jQuery Ajax call:

// custom jQuery script sample for GET request
jQuery(document).ready(function($) {

    const myScript = {
        ajax_url : "/wp-admin\/admin-ajax.php"
    }

    // This is the variable we are passing via AJAX
    let fruit = 'Banana';

    // This does the ajax request (The Call).
    $.ajax({
        url: myScript.ajax_url, // we define the target url for ourselves
        data: {
            'action':'example_ajax_request', // This is our PHP function below
            'fruit' : fruit // This is the variable we are sending via AJAX
        },
        success: function(data, response) {
            // This outputs the result of the ajax request (The Callback)
            window.alert(data);
            console.table(data, response);
        },
        error: function(errorThrown){
            window.alert(errorThrown);
        }
    });
});

And I just a little bit corrected your PHP function where I separated the GET request and the POST request for different responses (and I will create an Ajax POST request to this same function below in my post.

(in functions.php)

<?php

// example ajax call_user_func
// for Ajax GET and POST request
function example_ajax_request() {

    if ( $_SERVER['REQUEST_METHOD'] === 'GET' ) {            
        
        $fruit = $_REQUEST['fruit'];

        // Processes the fruit variable into an Apple
        if ( $fruit === 'Banana' ) {

            $fruit = 'Apple';

            echo json_encode(['fruit' => $fruit]);

        } else {

            $fruit = 'Kiwi';

            echo json_encode(['fruit' => $fruit]);

        }
        
        return true;

    }

    if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {

        // getting the body data from post request
        $request_body = json_decode(file_get_contents('php://input'));

        $fruit = $request_body->fruit;
        
        if ($fruit === 'Banana') {
            $fruit = 'Lemon';
        }
        
        return wp_send_json( $fruit, $status_code = null, 0 ) ;

    }

}    

// add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' ); // if your ajax call is in admin

add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' ); // if your ajax call is in front-end

And finally I created an Ajax POST request to the same PHP function with using vanilla javascript (I like it much more than jQuery...):

window.addEventListener('load', async function ajaxTesting(ev) {
      
    let fruit = 'Banana';

    const data = {
        'action':'example_ajax_request',
        'fruit' : fruit
    }
    const  ajax_url_post = "/wp-admin\/admin-ajax.php?action=" + data.action;

    try {
        const response = await fetch(ajax_url_post, {
            method: "POST",            
            body: JSON.stringify(data),
        });
        console.log("call was successful", response);
        console.log("call was successful", data);
    } catch (error) {
        console.error(`this call had an error: ${error.message}`);
    }

});

You can see above that for post request I defined the target URL a bit differently. The above functions are tested and working in Wordpress 6.2

I hope this will help you in creating working ajax functions in Wordpress.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.