Ajax call from frontend not working with wordpress

2k views Asked by At

Call to Ajax not working from frontend in WordPress,All i want to the data from db based on id,this is what i have tried so far.

//Frontend view

<a href="javascript:void(0)" onclick="getDetails(<?=$index;?>)" >
        <?php echo $value ?>
    </a>

//Functions.php

function my_enqueue() {
      wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/assets/js/ajax-script.js', array('jquery') );
      wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
 }

 add_action( 'wp_enqueue_scripts', 'my_enqueue' );
 add_action('wp_ajax_nopriv_more_posts', 'get_more_posts');

function get_more_posts(){
    // How to get id here to query for the database
    echo "Hello World";
    exit(); 
}

// Ajax scripts File
function getDetails(id)
{
jQuery.ajax({
    url: more_posts.ajax_url,
    type: "GET",
    data: {
        action: 'more_posts'
    },
    dataType: "html",
    success: function(response){
        alert(response);
    }
});
}

I am getting this error

reference error more_posts is not defined

2

There are 2 answers

0
Bilal Hussain On BEST ANSWER
//Frontend view

<a href="javascript:void(0)" onclick="getDetails(<?=$index;?>)" >
        <?php echo $value ?>
    </a>

//Functions.php

function my_enqueue() {
      wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/assets/js/ajax-script.js', array('jquery') );
      wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
 }

 add_action( 'wp_enqueue_scripts', 'my_enqueue' );
 add_action('wp_ajax_nopriv_more_posts', 'get_more_posts');

function get_more_posts(){
    // How to get id here to query for the database
    echo "Hello World";
    echo $_GET['id'];
    exit(); 
}

// Ajax scripts File
function getDetails(id)
{
var id = id;
jQuery.ajax({
    url:  url: my_ajax_object.ajax_url,
    type: "GET",
    data: {
        action: 'get_more_posts',
        id: id,
    },
    dataType: "html",
    success: function(response){
        alert(response);
    }
});
}

This should work! You dont need absolute path or var with 'href', url: my_ajax_object.ajax_url, is enough as you already added admin-ajax.php with wp_enqueue_script. Thanks

0
Guillermo Andres Fuentes Moral On

You mistake in

  url: more_posts.ajax_url

Because you localize script name is my_ajax_object

 wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

try this

 url: my_ajax_object.ajax_url