0
votes

Hello I am new and building an application in Flask and Javascript. I have a problem with sending data from Flask do JavaScript.

I have code in routes.py

@app.route('/mapaa',methods=['GET','POST'])
def mapa():
    user_id = current_user.get_id()
    slownik = {}


    if 'event_form' in request.form:
        name = request.form['name_event']
        all_data = Event.query.filter_by(name=name).all()
        for row in all_data:
            date_st_string = str(row.date_start)
            date_end_string = str(row.date_end)
            slownik = {'id':row.id,'date_st':date_st_string,'date_end':date_end_string,'type':row.type,'name':row.name,'len_route':row.len_route,'route':row.route}
        return jsonify(slownik)
    return render_template('mapaa.html', title='Mapa')

I want to send jsonify(slownik) to my code in JavaScript but I dont want to do it with render_template bacause it refresh a page and I need this data to display it on the map using JavaScript. I tried return jsonify(slownik) but it return me the data on new page. How I can send the data when the user click event_form button to JavaScript without refreshing page?

1
Welcome to SO! Make an AJAX request from your JS, for example, fetch('/mapaa', {method: 'post',body: data,}).then(res => res.json()).then(data => console.log(data)). See How do I post form data with fetch api? - ggorlen
Thank you for answer. I don't understand much of fetch and I don't know what I need to replace` data` in body. - helper
That's for you to decide--it's your POST request. data is form data built as shown in the link above. - ggorlen
So if I want do send slownik how I can do it? I need send it like variable or what? - helper
You may be a bit confused about the overall concept going on here. When you POST, you send a request to a server with a payload (some form data, JSON, text, etc). The server receives the POST request at an endpoint, does some processing or fetches DB results and sends a response back to the client. In this case, the client is the front-end JS code, the server is your Flask app. slownik looks rather odd because it'd only contain the last row's data, but the bottom line is that return jsonify(slownik) responds to the front-end POST request with whatever's in slownik. - ggorlen

1 Answers

0
votes

You can use ajax for sending post request without refreshing the page. Note- include jquery before this

<script src="https://code.jquery.com/jquery-3.1.0.js" ></script>

javascript code

$("#id_of_btn").click(function () { // make ajax request on btn click
  $.ajax({
    type: "POST",
    url: "/mapaa", // url to the function
    data: {
      name: $("#id_of_input_tag").val(), // value of the form
    },
    success: function (response) {
      console.log(response); // response contains the json
    },
  });
});

make sure you don't use form tag.

Edit: If you want to send more data via forms, you could use

data: $('form').serialize()

this will take the name attribute of input tag and add it in the request.data So if you have this

<input type="text" id="element_id" name="username" > 

You can use the value of name attribute like this request.data['username'] follow this tutorial