0

I am trying to write a WP function to work with both ajax and direct calls, something like this:

PHP

function some_function($var){
    $var = !empty($var) ? $var : $_POST['var'];
    echo $var;
    
    //or even

    $var = null;
    echo 'something';

    if(!empty($_POST['action'])) wp_die();
}

AJAX CALL

let ajaxurl = '███';
let data = {'action': 'somefunction','var':'foo')};
$.post(ajaxurl, data, function(response) {console.log(response);});

WP use

add_action( 'wp_ajax_somefunction', 'some_function',10,1);
add_action( 'wp_ajax_nopriv_somefunction', 'some_function',10,1);

Another WP use

some_function('bar');

However, any time I place $var as an accepted function argument, some_function($var), my ajax calls start returning a 500 error. So, something like this

function some_function(){
    $var = !empty($var) ? $var : $_POST['var'];
    echo $var;
}

works for ajax.

I tried looking up wp ajax & arguments, but the search results are always about the variables we pass through ajax, not the callback function arguments. The only thing I learned is that we have to add a number of accepted arguments into add_action()

What am I doing wrong?

Thank you.

...P.S. I found a funny workaround:

function some_function_ajax(){
    $var = $_POST['var'];
    some_function($var);
}
function some_function($var){
    echo $var;
} // =)

but still, what is the right way?


Jackob Peattie, thanks for the hint! So, the working code looks like this, then:

//JS (jQuery):
let data = {
   'action' : 'func',
   'var' : 'something',
   'nonce' : nonce
};
$.post(ajaxurl, data);

//add_action:
add_action( 'wp_ajax_func', 'func_ajax');
add_action( 'wp_ajax_nopriv_func', 'func_ajax');

//PHP:
function func_ajax(){
   //verify nonce
   if(empty($_POST['nonce']) || !wp_verify_nonce( $_POST['nonce'], 'myajax-nonce' ) ) wp_die();

    $var = $_POST['var'];
    func($var);

   //end ajax call
   wp_die();
}

function func($var){
    echo $var;
}

1 Answer 1

1

No arguments are passed to the AJAX callback function. Variables passed with the request are available in $_GET or $_POST. So if your function expects an argument, it can’t be used as the hooked callback directly.

Your workaround is the correct way to use a function that accepts arguments in an AJAX request.

0

Your Answer

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

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