0

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?

helper
  • 23
  • 6
  • 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?](https://stackoverflow.com/questions/46640024/how-do-i-post-form-data-with-fetch-api) – ggorlen Jun 06 '21 at 15:51
  • 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 Jun 06 '21 at 18:16
  • That's for you to decide--it's your POST request. `data` is form data built as shown in the link above. – ggorlen Jun 06 '21 at 18:25
  • So if I want do send `slownik` how I can do it? I need send it like variable or what? – helper Jun 06 '21 at 18:31
  • 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 Jun 06 '21 at 18:34
  • Yes you are right I still dont understand how it's work. I dont know what I need give in `body` I want have there data from `slownik`. So I need to create dictionary there? – helper Jun 06 '21 at 18:42
  • What do you mean by `body`? You show a somewhat-odd but (at a glance) basically working backend. Just write some JS and POST your data to it as the answer shows (I don't recommend using jQuery necessarily, but it gives the general idea...). You ask: how to send data from Flask to JS, well, this code already does exactly this -- sends a response to a POST request initiated by a client. The front-end simply needs to use AJAX instead of a traditional form submission so as to prevent a new page load. You want to inject the data into the document without a new page load. – ggorlen Jun 06 '21 at 18:43
  • I mean data from `slownik`. I copy that code and paste to my code but it return `data is no defined` and i don't know how and what I can put here. I don't understand AJAX. I guess that something will be there but I dont know how I can send there my `slownik`. – helper Jun 06 '21 at 19:12

1 Answers1

1

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

charchit
  • 1,492
  • 2
  • 6
  • 17
  • Thank you for answer. I did that i place this js code in my JavaScript but it return in console my html code of my `mapaa.html`. I did something wrong or I need to add something to this code ? – helper Jun 06 '21 at 18:14
  • So if I dont need form tag this line: `name = request.form['name_event']` in my Flask code is unnessecary because I use `data: {name: $("#id_of_input_tag").val() },` and this replaces it right ? – helper Jun 06 '21 at 18:24
  • No!! don't copy the answer as it is, it need changes , for eg. where I wrote id_of_input there you need to include of the value of the input tag which is used in html like `$("#name").val()1 where name is the id of the input – charchit Jun 06 '21 at 19:13
  • Yes I know i did it. But it returns me html code of my `mapaa.html`. I need to add something else to return json and my data from `slownik`? – helper Jun 06 '21 at 19:15
  • Yes I did it but it returns `jquery-3.4.1.min.js:2 POST http://127.0.0.1:5000/mapaa 500 (INTERNAL SERVER ERROR)` – helper Jun 06 '21 at 19:24
  • if 'event_form' in request.form: change this to this if request.method == "POST":, don't remove request.form['name_event'] I was taking about the form tag in html
    ...
    ,also the name in data object in json should be the key in request.form[] like [`name`]
    – charchit Jun 06 '21 at 19:27
  • can you please tell me the logs , if you haven't turn on debug mode then do this in app.run(debug=True). – charchit Jun 06 '21 at 19:28
  • ``` \app\routes.py", line 109, in mapa name = request.form['name_event'] File "C:\Users\baute\AppData\Local\Programs\Python\Python38\Lib\site-packages\werkzeug\datastructures.py", line 442, in __getitem__ raise exceptions.BadRequestKeyError(key) werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'name_event'``` – helper Jun 06 '21 at 19:40
  • that's it the request.form doesn't have `name_event` change it to `name` which was defined in the ajax function data parameter `**name**: $("#id_of_input_tag").val()` – charchit Jun 06 '21 at 19:42
  • Yeees! Now it's work ! Thank you very much! – helper Jun 06 '21 at 19:45
  • welcome, if you want you can mark this as correct answer – charchit Jun 06 '21 at 19:47