0

My Flask application uses jQuery to dynamically generate line by line of data from a SQLalchemy database. I'm using a forEach loop to generate each element, based on the length of the database. However, this does not work on mobile devices (it doesn't show), but it works on all browsers in PC. Does anyone have any idea why?

HTML and jQuery '''

{%extends "layout.html" %} {% block content %}
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
        var i=0;
        $.ajax({
            url: "http://localhost:5000/get_data",
        }).done(function(data) {
            data_parsed=jQuery.parseJSON(data);
            data_parsed.forEach(function(dt){
                #HERE IS THE PROBLEMATIC PART
                $("pquestions").append("<p>"+ dt['id'] +". " + dt['question'] + " " +
                                        "<input id=\""+"question"+i+"\">" + "</input>" +
                                        "<button type=\""+"button"+"\" id=\""+i+"\">" +
                                        "</p>");
                i++;

            });
            //$('#questiontests').html(jQuery.parseJSON(data)['0']["question"]).text();
            //console.log(jQuery.parseJSON(data).length);
        });

  });
</script>

<script type="text/javascript">
    $(document).on("click",'button',function() {
        var x = document.getElementById("question"+this.id).value;
        var current_id=this.id
        $.ajax({
            url: "http://localhost:5000/get_data",
        }).done(function(data) {
            data_parsed=jQuery.parseJSON(data)
            console.log(data_parsed[current_id]["answer"])
            if (x==data_parsed[current_id]["answer"]){
                sweetAlert(
                    {
                    title: "Juist!",
                    icon: "success"
                    })
            } else {
                sweetAlert({
                    title: "Ontjuist!",
                    icon: "warning",
                    text: "Uw response is " + x + " maar het antwoord is " + data_parsed[current_id]["answer"],
                    })
            }
            console.log("button click");
        });
    });
</script>

<section class="page-section" style="background-color:lightblue" id="about">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8 text-center">
                <h2 class="text-black-50 mt-0">Dutch oefening</h2>
                <h5 class="text-black-50 mt-0 font-italic">
                    Hier kun je je eigen oefening toevoegen, geen duplicaten mogelijk:
                </h5>
                <form action="/add_question" method="post">
                  <label for="fname">Vraag:</label>
                  <input type="text" id="fname" name="fname">
                  <label for="lname">Antwoord:</label>
                  <input type="text" id="lname" name="lname">
                  <input type="submit" value="onslaan">
                </form>
                <h5 class="text-black-50 mt-0 font-italic">
                    Hier kun je een rij verwijderen:
                </h5>
                <form action="/delete" method="post">
                  <label for="deletes">Rij om te verwijderen:</label>
                  <input type="text" id="deletes" name="deletes">
                  <input type="submit" value="verwijder">
                </form>
                <h5 class="text-black-50 mt-0 font-italic">
                    Schrijf de vertaling van elke zin, en druk op de knop om te controleren
                </h5>
                <pquestions id="#all_questions">
                </pquestions>
            </div>
        </div>
    </div>

</section> {% endblock %}

server:

from flask import request, Flask, render_template, send_from_directory
from flask_sqlalchemy import SQLAlchemy
import requests
import json
import jsonpickle

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 1
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///site.db'

#Create database instance for dutch learning
db = SQLAlchemy(app)
class Tests(db.Model):
     id=db.Column(db.Integer, primary_key=True)
     question=db.Column(db.String(200),unique=True)
     answer = db.Column(db.String(200), unique=False)

     def __repr__(self):#Redefine what print(object) is
         return '{} {}'.format(self.question,self.answer)

@app.route('/dutch_training',methods=['GET','POST'])
def dutch_training():
    data=Tests.query.all()
    return render_template("dutch_training.html",data=data)

if __name__ == '__main__':
    app.run(debug=True,port=5000,host='0.0.0.0')

On PC:

enter image description here

On iPhone:

enter image description here

2
  • 1
    Might not be recognizing your custom element <pquestions></pquestions> Commented Sep 8, 2020 at 6:46
  • For us to test: please click edit and then [<>] snippet editor. Post a minimal reproducible example WITHOUT server code and AJAX (which likely work fine) Just with a plain object, HTML, CSS and scripts Commented Sep 8, 2020 at 6:49

2 Answers 2

1

Got it; I need to use the server's IP address instead of localhost

Sign up to request clarification or add additional context in comments.

Comments

0

Is there any reason why you use <pquestions>? could you test it with normal <div id="all_questions"> without "#" and then use selector in js as $('#all_questions').append() and i will recoment use template string:

your append:
"<p>"+ dt['id'] +". " + dt['question'] + " " +
"<input id=\""+"question"+i+"\">" + "</input>" +
"<button type=\""+"button"+"\" id=\""+i+"\">" +
"</p>"
my recomendation:
`<div>
  ${dt['id']}. ${dt['question']} <input id="${'question' + i}"></input>
  <button type="button" id="${i}">
</div>`

I think its not good practice to add "input or button" tags inside p tag.

if template doesn't work with append function you can use:

var templateName = `<div>
  ${dt['id']}. ${dt['question']} <input id="${'question' + i}"></input>
  <button type="button" id="${i}">
</div>`

$('#all_questions')[0].insertAdjacentHTML('beforeend', templateName);

More about insertAdjacentHTML here: https://developer.mozilla.org/pl/docs/Web/API/Element/insertAdjacentHTML

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.