How to use wordpress functions in an ajax call

ajax, function, jquery, wordpress

Solution

WordPress provides an Ajax Url that you should use along with a complete Ajax API.

You need to create a jQuery function.

Example:

jQuery(document).ready(function($) {

    var data = {
        action: 'my_action',
        whatever: 1234
    };

    jQuery.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});

The ajaxurl var is always available on the admin side. If your using it on the front end you need to define it.

Then a PHP function where you can run your query. The PHP function must get attached to the `wp_ajax_your_action` action.

Example:

add_action('wp_ajax_my_action', 'my_action_callback');

function my_action_callback() {
    global $wpdb; // this is how you get access to the database

    $whatever = intval( $_POST['whatever'] );

    $whatever += 10;

        echo $whatever;

    die(); // this is required to return a proper result
}

The `wp_ajax_your_action` action is for admin if you need to use it on the front end the action would be `wp_ajax_nopriv_your_action`

Problem

I wanted to know if there is a way to use function like query_post() in an ajax call ? Let's say i'm calling the file _inc/ajax.php I want to be abble to use the wordpress functions, but i don't know why. Can someone help me for that ? Thanks a lot :)

Original source