简体   繁体   中英

AJAX functions acting on page load rather than button click

This is the first time that I am trying to implement AJAX on a site. It seems my code runs my AJAX functions on $(document).ready() . How can I configure my code to declare these functions without them running when a page has loaded?

The code:

$(document).ready(function(){

    var score = 0; //set result score to start at 0

    $("#start").click( renderNewQuestion()); // get and render a new question when user clicks start
    $("#nextQuestion").click( postResult()); // post result then get and render new question when user clicks next question
    $("#answer-toggle").click( function(){
        $("#question").hide(); //hide question div
        $("#answer").show(); //show answer div
    });
    // omitted code to calculate score as irrelevant

    var newQuestionHTML; //save HTML for new question in a variable

    function getChunk(){
        $.ajax({
            type: 'GET',
            url: '/getchunk/',
            success: function(data) {
                newQuestionHTML = html(data)
            },
            error: function() {
                alert('Something went wrong when getting the next question');
            }
        });
    }

    function renderNewQuestion(){
        getChunk;
        $("review-row").replaceWith(newQuestionHTML);
    }

    function postResult(){
        var result = {
            score: score,
            csrfMiddlewareToken: $("input[name='csrfmiddlewaretoken']").val(),
            chunkID: $("#chunk-id").val(),
        };

        $.ajax({
            type: 'POST',
            url: '/postresult/',
            data: result,
            success: renderNewQuestion(),
            error: function() {
                alert('Something went wrong when posting the results');
            }
        });
    }

});

In this line $("#start").click( renderNewQuestion()); you should pass the function, not execute it, so remove the parenthesis after the function name.

This is a better way to write it BTW:

$("#start").on("click", renderNewQuestion);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM