0

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');
            }
        });
    }

});
Era
  • 141
  • 1
  • 4
  • 13
  • 1
    Possible duplicate of [What is the difference between a function call and function reference?](http://stackoverflow.com/questions/15886272/what-is-the-difference-between-a-function-call-and-function-reference) or http://stackoverflow.com/q/7102413/215552 or http://stackoverflow.com/questions/10101899/javascript-onclick-event-getting-called-automatically or http://stackoverflow.com/questions/29526556/javascript-onclick-function-is-called-immediately-not-when-clicked – Heretic Monkey Dec 07 '16 at 21:06

1 Answers1

1

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);
David Gomez
  • 2,672
  • 2
  • 15
  • 27