最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

AJAX jQuery post frontend returning failed to load resource status 400

programmeradmin1浏览0评论

I've created a custom post template for a front-end question bank/quiz in which I have two elements:

  1. A div which displays question text
  2. A button when pressed should trigger an ajax query to get the next question from a database

Code in functions.php

//Load ajax object for question bank
add_action('wp_enqueue_scripts', 'my_enqueue');
function my_enqueue(){
    wp_enqueue_script( "question-refresh", get_stylesheet_directory_uri() . "/js/question-refresh.js", array("jquery") , null, true);
    $question_nonce = wp_create_nonce( 'question' );
    wp_localize_script(
        'question-refresh',
        'my_ajax_obj',
        array(
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'nonce' => $question_nonce,
        )
    );
    
}

add_action('wp_ajax_nopriv_get_question', 'get_question_from_database');
add_action('wp_ajax_get_question', 'get_question_from_database');

function get_question_from_database(){
    check_ajax_referer( 'question' ); //Checks nonce
    echo "<script type='text/javascript'>alert('SCRIPTS LOADED');</script>";
    $question_number = rand(1,4);
    $query = "SELECT * FROM `questions`
                WHERE question_number = $question_number";
    $result = $mysqli->query($query) or die($mysqli->error.__LINE__);
    $question = $result->fetch_assoc();
    echo json_encode(array("success" => true, "question-text"=>$question['question_text']));
    exit;
}

The code I have in my custom post template is as following:

<main>
    <div class="container">
        <div>Question 1 of 5</div>
        <p id="question-container">
        </p>
        <button id="next-question" type="button">Next</button>
    </div>
</main>

I have a separate js file stored in my-child-theme/js/question-refresh.js I think I have isolated where the issue is coming from. I have obviously done something wrong with the jQuery.post as it doesn't seem to be running. I am new to jQuery and have just been following other questions and tutorials. Would really appreciate if someone could spot what I am doing wrong. Many thanks!

jQuery(document).ready(function($) {
    
    $("#next-question").click( function() {
        console.log("Hello");
        $.post(
            my_ajax_obj.ajax_url, 
            { 
                _ajax_nonce: my_ajax_obj.nonce, 
                "action": "get_question"
                
            }, 
            function(response) {
                console.log("Hello");
                console.log(response);
                $("#question-container").text(response.question-text);
        });
    });
});

I've created a custom post template for a front-end question bank/quiz in which I have two elements:

  1. A div which displays question text
  2. A button when pressed should trigger an ajax query to get the next question from a database

Code in functions.php

//Load ajax object for question bank
add_action('wp_enqueue_scripts', 'my_enqueue');
function my_enqueue(){
    wp_enqueue_script( "question-refresh", get_stylesheet_directory_uri() . "/js/question-refresh.js", array("jquery") , null, true);
    $question_nonce = wp_create_nonce( 'question' );
    wp_localize_script(
        'question-refresh',
        'my_ajax_obj',
        array(
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'nonce' => $question_nonce,
        )
    );
    
}

add_action('wp_ajax_nopriv_get_question', 'get_question_from_database');
add_action('wp_ajax_get_question', 'get_question_from_database');

function get_question_from_database(){
    check_ajax_referer( 'question' ); //Checks nonce
    echo "<script type='text/javascript'>alert('SCRIPTS LOADED');</script>";
    $question_number = rand(1,4);
    $query = "SELECT * FROM `questions`
                WHERE question_number = $question_number";
    $result = $mysqli->query($query) or die($mysqli->error.__LINE__);
    $question = $result->fetch_assoc();
    echo json_encode(array("success" => true, "question-text"=>$question['question_text']));
    exit;
}

The code I have in my custom post template is as following:

<main>
    <div class="container">
        <div>Question 1 of 5</div>
        <p id="question-container">
        </p>
        <button id="next-question" type="button">Next</button>
    </div>
</main>

I have a separate js file stored in my-child-theme/js/question-refresh.js I think I have isolated where the issue is coming from. I have obviously done something wrong with the jQuery.post as it doesn't seem to be running. I am new to jQuery and have just been following other questions and tutorials. Would really appreciate if someone could spot what I am doing wrong. Many thanks!

jQuery(document).ready(function($) {
    
    $("#next-question").click( function() {
        console.log("Hello");
        $.post(
            my_ajax_obj.ajax_url, 
            { 
                _ajax_nonce: my_ajax_obj.nonce, 
                "action": "get_question"
                
            }, 
            function(response) {
                console.log("Hello");
                console.log(response);
                $("#question-container").text(response.question-text);
        });
    });
});
Share Improve this question edited Feb 1, 2021 at 2:30 allquiet1984 asked Jan 31, 2021 at 23:52 allquiet1984allquiet1984 32 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

There's two problems that I see.

Firstly, your add_action('wp_ajax_nopriv_get_question',... code is inside your template, but your template is not going to be loaded when the request is sent to wp-admin/admin-ajax.php, which does not load templates. The callback code and the code that hooks it need to go in your theme's functions.php file.

Secondly, you have only hooked the callback for logged-out users (nopriv_). This means that the code will not work when you are logged in. You need to hook for both logged-in and logged-out users:

add_action('wp_ajax_get_question', 'get_question_from_database');
add_action('wp_ajax_nopriv_get_question', 'get_question_from_database');
发布评论

评论列表(0)

  1. 暂无评论