How do I send an ajax request and get a response back from a function?

$.ajax is very simple and you can append more parameters easily in the data: {action:'my_test_ajax'} line, try this:

var target="http://"  +  window.location.hostname  + '/wp-admin/admin-ajax.php';
$.ajax({
    url: ajax,
    data: {action:'my_test_ajax'},
    type: 'post',
    success: function(data){
        console.log(data, data.title, data.content)
    }
});

Make sure the target points exactly to admin-ajax.php or set a global variable (or using localize script) to add a variable where you store the path to admin-ajax.php which is admin_url('admin-ajax.php') in case of confusion.

$.ajax does parse JSON data by default, if working with other methods that return the response as is (string) then simply use JSON.parse(response) method. JSON that’s because you use wp_send_json($resp) which returns a JSON object response in the endpoint.

Here’s an example of adding more data to the request:

Using append method to the data variable or keeping it short and simple as data: {action:'my_test_ajax', name: 'dave', network: 'wpse'} and from the my_test_ajax function you can get these data by $_REQUEST[tag] e.g $_REQUEST['name']

$.get ( $_GET ) method:

This one is even more simple and takes less code:

$.get( target="/wp-admin/admin-ajax.php?action=my_test_ajax", function( data ) {
    console.log( data )
});

Remember to use $_REQUEST in your PHP script because it merges all $_GET, $_POST and $_COOKIE data sets. Unless of course you are sure about the method you’re working with.

Hope that helps.

Leave a Comment