Dylan Richards
Dylan Richards

Reputation: 786

How to update variable on button press?

I have here some JavaScript with jQuery and AJAX.

On the click of a button, the user should be served with an image of a die that corresponds with a random number from 1 to 6. What's happening here is that the result is being calculated only once (at page load) and does not update whenever I click the button, which is why I'm getting the same roll result every time. How can I achieve the result I desire?

$(document).ready(function () {        
  $('.roll').click(function(e){
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: '/rolls',
        data: result,
        success: function() {
            $('h1').replaceWith('<h1>Rolled</h1>');
            $('#die').replaceWith(image)
        }
    })
  });   
  result = Math.floor(Math.random() * 6) + 1;
  image = "<img src='" + result + ".png' alt='yoo'>";   
});

Upvotes: 0

Views: 62

Answers (2)

PeterKA
PeterKA

Reputation: 24638

The re-calculation has to be done in click handler but before the ajax call.

$(document).ready(function () {
    $('.roll').click(function(e){
        e.preventDefault();
        var result = Math.floor(Math.random() * 6) + 1;
        var image = "<img src='" + result + ".png'";
        $.ajax({
            type: 'POST',
            url: '/rolls',
            data: result,
            success: function() {
                $('h1').replaceWith('<h1>Rolled</h1>');
                $('#die').replaceWith(image)
            }
        })
    })
    .trigger('click');
 });

Upvotes: 1

dss
dss

Reputation: 470

you need to move these lines

result = Math.floor(Math.random() * 6) + 1; image = "";

to the beginning of the ajax success function. the way you have it written now its not part of the click function

also add var result ="default.png" before the click function

Upvotes: 0

Related Questions