-1

This is my function in flask which is rolling 6 side dice:

@bp.route('/character', methods=('GET', 'POST'))
@login_required
def character():
    throws = []
    def roll_1d6():
        return random.randint(1,6)

    def roll_4d6(num_dice):
        for i in range(num_dice):
            throws.append(roll_1d6())

        return json.dumps(throws)
    return render_template('dd_roller/create_character.html', throws=throws) 

I was also using make_response(json.dumps(throws)) and jsonify(throws)

And my javascript:

<script>
function getData() {
fetch('/character')`your text`
   .then(response => response.json())
   .then(throws => {
    document.getElementById("get_data").innerHTML = "You rolled a " +throws;
     console.log(throws);
              
          })
         
    }
  </script>

  <button onclick="getData()">ROLL</button>
  <p id="get_data"></p>

Is giving me all the time error: Uncaught (in promise) SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON

How can I make button which will fetch() value from my function in flask?

  • Inside the `character()` function, you define some other functions, but those other functions are never _called_. So `character()` does not return anything. – John Gordon Feb 17 '23 at 15:46
  • 1
    Also, there is a `@login_required` decorator. If you try to access this url but you are not logged in, I think you are redirected to the login page, which of course is not json. – John Gordon Feb 17 '23 at 15:47
  • I added last line to character() sory. – Rafał Tomaszewski Feb 17 '23 at 16:02
  • @RafałTomaszewski yes, but there will be other things you will probably want to do on the server so it's probably still worth figuring it out. You will need more complicated handling logic in your JS to check the return code and deal with the error. Having an async operation with no error handling is never a good idea. – Jared Smith Feb 17 '23 at 16:07
  • Since you're returning `render_template(...)`, that means `character()` is returning a plain html page, not json... – John Gordon Feb 17 '23 at 16:08

1 Answers1

0

I don't know if it's right way to do it but it work for me that way:

I made new endpoint in init.py file.

@app.route('/attribute', methods=('GET', 'POST'))
def attribute():
    throws = []
    def roll_1d6():
        return random.randint(1,6)

    def roll_4d6(num_dice):
        for i in range(num_dice):
            throws.append(roll_1d6())
        jsonify(throws)
        return throws
    roll_4d6(4)
    return jsonify(throws)

And it work enter image description here