admin管理员组

文章数量:1335877

I am implementing some changes to my website's page with AJAX.

I have enqueued my js file in functions.php

add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {

    wp_register_script( "index", get_stylesheet_directory_uri() . '/index.js', array('jquery') );
    wp_localize_script( 'index', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); 
    wp_enqueue_script(
        'index', // name your script so that you can attach other scripts and de-register, etc.
        get_stylesheet_directory_uri() . '/index.js', // this is the location of your script file
        array('jquery') // this array lists the scripts upon which your script depends
    );

}

And then I have created an AJAX request in my index.js file

jQuery(document).ready(function ($) {
  //Ajax Call for changing to the best deals of the day
    $('.best-deals-day').click(function () {

        jQuery.post(
            myAjax.ajaxurl, {
                'action': 'homepage-best-deals-daily',
            },

            function (response) {
                $('.popular-coupons-section-list').html(response);
            }

        );
    });
});

And I have included the wp_ajax function in my template page

add_action( 'wp_ajax_homepage-best-deals-daily', 'payuoc_homepage_best_deals_of_the_day' );
add_action( 'wp_ajax_nopriv_homepage-best-deals-daily', 'payuoc_homepage_best_deals_of_the_day' );

function payuoc_homepage_best_deals_of_the_day(){

//Code content Here

wp_die();
}

But in the front end, it is resulting in an error POST .php 400

If I move the wp_ajax action and its associated function to functions.php, the code is working fine. What is the actual problem? And I don't want to move it to functions.php and want to keep it in template page.

本文标签: wp enqueue scriptI am getting Adminajaxphp 400 Error