ajax, right way to do it and make it works?

I’m new to wordpress but have knowledge in php and javascript.

I read a lot of blogs about ajax call in wordpress. I also read some posts on this forum.
However, I still have some difficulties making an ajax call with wordpress.

Read More

It’s a little confusing in my mind where add_action and hook must be written (inside my custom php function file or inside function.php file? or in an other way).

When my jquery script is called, wp_ajax is not defined…
I don’t understand how my jquery script can get wp_ajax url or other variable from php before it is ran.

Here my different scripts:

In my function.php (I really don’t know if I need to put this here or in my custom php file):

wp_enqueue_script('load_post', get_template_directory_uri().'/js/load_post.js', array('jquery'), '1.0', 1 );
wp_localize_script( 'load_post', 'wp_ajax',
        array( 'url' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce('ajax_nonce') )); 

In load_post.php

<?php

add_action('wp_ajax_load_post', 'load_post_callback');
add_action('wp_ajax_nopriv_load_post', 'load_post_callback');

function load_post_callback() {

if (isset($_POST['post_ids'])) {

    $nonce = $_POST['nonce']; 
    if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) ) {
        die ( 'Interdit !');
    }

    $ids = array(); 
    $ids[] = $_POST['post_ids'];

    $posts_per_page = 8;
    global $wp_query;
    query_posts(array('post_type' => array('post', 'portfolio'), 'post__not_in' => $ids, 'posts_per_page' => $posts_per_page));
    while (have_posts()) : the_post();

    $post_type = get_post_type( $post->ID );
    if ($post_type == 'post') {
        $post_type = 'blog';
    }
?>

//I do some stuff echo...

<?php
    endwhile;
    wp_reset_query();
    }
}
?>

And load_post.js

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

    jQuery('#next-container').click(function() { 

        var IDs = [];
        $(".element").each(function(){ IDs.push(this.id); });

        $('#next-container').html('loading');

        $.ajax({
            type: 'POST',
            url: wp_ajax.url,
            data: {  action: 'load_post',  
                     ajax_nonce: wp_ajax.nonce,
                    'post_ids': IDs,  
                  },  //{'post_ids[]': IDs },//'post_ids='+IDs,
            success: function(data) {
                    $('#next-container').html('');  
                    $container.isotope( 'insert', $(data));

                    }
                })
        })
})

Related posts

2 comments

  1. In your functions.php file you should add an action to enqueue your scripts.

    <?php
    function my_enqueue_scripts() {
        wp_enqueue_script(
            'load_post', 
            get_template_directory_uri() . '/js/load_post.js', 
            array( 'jquery' ), 
            '1.0', 
            1
        );
        wp_localize_script( 
            'load_post', 
            'wp_ajax',
            array( 
                'url' => admin_url( 'admin-ajax.php' ), 
                'nonce' => wp_create_nonce( 'ajax_nonce' )
            )
        );
    }
    add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
    
  2. I am also having some problems, This is how I am calling the Fucntion via Ajax on Windows scroll

        $(document).live('scroll',(function(){
            // if ($(window).scrollTop() + $(window).height() == $(document).height())
            if ($(window).scrollTop() == $(document).height() - $(window).height())  {
              LoadonButton();
            }
        }));
    

    function LoadonButton (){
    var sessionCommentId =$(“.message_box:last”).attr(“id”);
    jQuery(‘#slick-slidetoggle’).show();
    jQuery.ajax({
    type:’POST’,
    url: ‘http://dino-dev.com/foodie/wp-admin/admin-ajax.php‘,
    data: {
    action: ‘HomeComments’,
    number: ’10’,
    CommentLoadedID:sessionCommentId
    },
    success: function(data, textStatus, XMLHttpRequest){

        jQuery(".comment_box:last").after(data);  
        },  
    error: function(MLHttpRequest, textStatus, errorThrown){  
    

    }
    }); }

    But I am having trouble with the plugins I am calling in HomeComments. The plugin functions are called but the options table is not populated or other things are missing.
    How do I make sure my plugins are loaded properly. When I call this function directly it works perfectly.

Comments are closed.