4

I've been trying to implement the recommendation by @SagiveSEO in this thread: Proper way to load a single post via Ajax?

The idea: click a button and load a post via AJAX. The idea being that you'll have a tree of buttons to allow people to navigate quickly to useful content.

Unfortunately, it fails.

In the console I get the message "ReferenceError: ajax_object is not defined" which refers to the line "$.post(ajax_object.ajaxurl..."

What am I doing wrong?

Here's my HTML:

<button class="get_project" data-postid="3300">PROJECT NAME</button>
                <div class="postcontainer"></div>

Here's my Javascript:

    jQuery(function($){
    $('.get_project').click(function() {
        var postid = $(this).data('postid'); // Amended by @dingo_d
        $.post(ajax_object.ajaxurl, {
            action: 'my_load_ajax_content ',
            postid: postid
        }, function(data) {
            var $response   =   $(data);
            var postdata    =   $response.filter('#postdata').html();
            $('.postcontainer').html(postdata);
        });

    })
    //alert( "hello world" );
});

and here is the php from my functions.php file:

function my_load_ajax_content () {

    $pid        = intval($_POST['post_id']);
    $the_query  = new WP_Query(array('p' => $pid));

    if ($the_query->have_posts()) {
        while ( $the_query->have_posts() ) {
            $the_query->the_post();

            $data = '
            <div class="post-container">
                <div id="project-content">
                    <h1 class="entry-title">'.get_the_title().'</h1>
                    <div class="entry-content">'.get_the_content().'</div>
                </div>
            </div>
            ';

        }
    }
    else {
        echo '<div id="postdata">'.__('Didnt find anything', THEME_NAME).'</div>';
    }
    wp_reset_postdata();


    echo '<div id="postdata">'.$data.'</div>';
}

// Next two lines corrected - thanks @dingo_d    
add_action ( 'wp_ajax_my_load_ajax_content', 'my_load_ajax_content' );
add_action ( 'wp_ajax_nopriv_my_load_ajax_content', 'my_load_ajax_content' );

Also required in functions.php within the script enqueuing function:

wp_enqueue_script( 'myajaxpostloader',  get_template_directory_uri().'/js/ajax.js', array( 'jquery' ), '1.0', true );

wp_localize_script( 'myajaxpostloader', 'ajax_object', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' )
));

(note that my Javascript is saved as /js/ajax.js where /js/ is a subdirectory of the Wordpress theme).

1 Answer 1

17

You didn't localize your ajax object. In Twenty fifteen theme you'd do it like this - in functions.php you'd put

wp_localize_script( 'twentyfifteen-script', 'ajax_object', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
));

Where your scripts are enqueued.

In your theme be sure to use proper handle - in stead of 'twentyfifteen-script' put the one where your ajax code is in. So if your ajax JavaScript is located in a file called custom.js, and you've enqueued that script with the handle custom_js, then you'd put

wp_localize_script( 'custom_js', 'ajax_object', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
));

After you've enqueued that script. All in all in your functions.php you'd put something like this:

add_action('after_setup_theme', 'mytheme_theme_setup');

if ( ! function_exists( 'mytheme_theme_setup' ) ){
    function mytheme_theme_setup(){
        add_action( 'wp_enqueue_scripts', 'mytheme_scripts');
    }
}

if ( ! function_exists( 'mytheme_scripts' ) ){
    function mytheme_scripts() {
        wp_enqueue_script( 'custom_js', get_template_directory_uri().'/js/custom.js', array( 'jquery'), '1.0.0', true );
        wp_localize_script( 'custom_js', 'ajax_object', array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
        ));
    }
}

Or at the very least look for such code and just place the localization there :)

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, @dingo_d - I did in fact enqueue and localize the script, but I didn't really understand the localize_script code, so this is a big help. However, my script now returns 0 as the HTML result. Any idea why?
Be sure that var postid = $(this).attr('data-postid'); returns correct post id. I'd use var postid = $(this).data('postid'); instead.
Thanks, @dingo_d, but that's not the problem - there's something more fundamental. I tried changing the function to this... function my_load_ajax_content () { echo 'hello world'; } ...but it still returns 0 every time. Any idea what's wrong?!
Your actions should be: add_action ( 'wp_ajax_my_load_ajax_content', 'my_load_ajax_content' ); add_action ( 'wp_ajax_nopriv_my_load_ajax_content', 'my_load_ajax_content' );
Glad I could help :) I have a tutorial, and there is a question here that I answered about using AJAX, feel free to check it out here :)
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.