excessive rice eater
excessive rice eater

Reputation: 95

how to properly get data from javascript to my python flask backend using XMLHttpRequest?

So I am trying to send a value to my backend flask python and process the data there and return it back, but after trying for hours all I got are error codes, 400 or 500. Please help me!

Here's my js code:

var keyword = document.getElementById("keyword").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '/searchresults', true);
xmlhttp.send("keyword=" + keyword);
console.log("SUCCESSFULLY SENT");

and my python code:

@app.route("/searchresults")
def test():
 return request.args.get['keyword']

my form:

<form id="searchform">
<label for="keyword">Keyword <span class="required">*</span> </label>
<input type="text" id="keyword" name="keyword" size="15" required>
</form>

EDIT:

I checked the network to make sure that the request is sent. Please correct me if it's not. enter image description here

Upvotes: 1

Views: 1737

Answers (1)

Codebling
Codebling

Reputation: 11382

You are trying to send a request body (xmlhttp.send("keyword=" + keyword)) with the keyword, but you are using the GET HTTP method, which does not allow a request body, so keyword=bla will never be part of the request.

Pass variables with a GET request

xmlhttp.open('GET', '/searchresults?keyword=' + keyword, true);
xmlhttp.send();

The Flask code is also wrong. .get() is a function, but it's being used as if it were a dictionary.

Call it as a function:

keyword = request.args.get('keyword')

Pass variables with a POST request

xmlhttp.open('POST', '/searchresults', true);
xmlhttp.send("keyword=" + keyword);

You'll have to change your Flask code to look in the request body instead of the args:

keyword = request.form.get('keyword')

Upvotes: 1

Related Questions