• Hi there,
    I’ve made a couple of plugins so far, including ajax requests. I’ve always used jQuery for that, but since I’m learning to use some more pure JS, I’ve ran into trouble.
    I’m trying to make a POST request to the plugin it’s core file like:

    const params = {
    	'action': 'test_method',
    	'name' : 'Jan',
    	'age' : '25',
    	
    };
    const options = {
    	method: 'POST',
    	body: JSON.stringify( params ),
    };
    fetch(wp.ajax_url+'?action=test_method', options)
    .then(response => response.json())
    .then(data => console.log(data));

    As you can see I tried sending the action through the url and through the body.
    And as simple as this function, I just try to return the name that I’ve sent. But it’s returning null:

    add_action('wp_ajax_nopriv_test_method', 'test_method');
    add_action('wp_ajax_test_method', 'test_method');
    function test_method(){
    	$test = $_REQUEST['name'];
    	wp_send_json($test);
    	// wp_send_json('test');
    }

    Does anyone know what I’m doing wrong?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Murali

    (@murali-indiacitys)

    try like fetch(wp.ajax_url+'?action=test_method&name=Jan&age=25')
    Pass parameters as search params like above,
    Since you are using action in search params then concatenate all other params in same url as search params, so it will be passed to ajax routine and returned back to javascript

    MK

    (@mkarimzada)

    I think you forgot to localize the script or pass the ajax_url to it. ajax_url is a global variable defined in WordPress backend, however it’s not defined in the frontend and you need manually pass it via wp_localize_script().

    Thread Starter janmoes

    (@janmoes)

    I was able to fix it. Normally I use jQuery, and I figured out, that jQuery sends data like something as FormData or URLSearchParams. So now I made an object filled with my fields and converted those in a URLSearchParams object!

    Thanks

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Ajax call not being able to return sent data’ is closed to new replies.