Getting wordpress to play nice with AJAX

How do I use WP functions from AJAX calls. I’ve looked at the documentation for creating plugins that use ajax, but I couldn’t figure out how to apply that to regular pages and posts.

Is there an easy way to just load everything without using their API? I have my way I like to do ajax and would rather not use their stuff.

Read More

This is a fluff version of my code:

Javascript (jQuery):

$('.action.next_posts').click(function() {
        var last_date = $(this).attr('title');
        //alert();
        $.ajax({
            url: WP_DIR+'functions.php?action=get_next_posts',
            type: 'POST',
            data: {date : last_date},

            success: function(response) {
                alert(response);
            },

            error: function(error) {
                alert("error");
            }
        });

    });

Functions.php (PHP):

// AJAX controller

if(isset($_GET['action'])) {
    require_once('../../../wp-config.php');

    require_once('../../../wp-includes/classes.php');
    require_once('../../../wp-includes/functions.php');

    wp();
    echo 'ok';
    echo bloginfo('name'); // NOT WORKING. TRIED adding actions..
    return;
}

Related posts

Leave a Reply

1 comment

  1. The following solution should work. You are going to go ahead and post directly to the WordPress installation and intercept the request before WordPress does all the querying that it would normally do. There are some caveats to this method, one of which being that some caching methods will interfere with it, but it should work fairly well for your purposes.

    Besides, you said you didn’t want to use the specified WordPress API, so this should be right up your alley.

    JavaScript:

    jQuery(document).ready(function($) {
        $('.action.next_posts').click(function(event) {
            event.preventDefault();
            var last_date = $(this).attr('title');
            $.ajax({
                url: '/',
                type: 'post',
                data: {date : last_date, action: 'get_next_posts'},
    
                success: function(response) {
                    alert(response);
                },
    
                error: function(error) {
                    alert("error");
                }
            });
    
        });
    });
    

    functions.php

    add_action('parse_request','my_request_parser');
    function my_request_parser($wp) {
        if( 'get_next_posts' == $_POST['action'] ) {
            echo 'ok';
            bloginfo('name');
            exit();
        }
    }