1

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

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

9 Comments

I tried using the GET request and when i tried to do "keyword = request.args.get('keyword')" in my backend, it still gives 500 internal server error when I visit link 127.0.0.1:5000/searchresults. It is saying that request.args.get('keyword') returns a null. If I use request.args, then i see an empty dictionary.
@excessivericeeater hmm. Thinking.
@excessivericeeater what is the error you're seeing from Flask?
Works for me. What object type is keyword? Can you check the DevTools in your browser to ensure that keyword is being sent? Did you from flask import request ?
The error is: TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement. and yes I did from flask import *. I checked the network in my DevTools and I am sure that it is being sent. What I'm trying to do is that I assigned the function to a button then when i click the button, the function sends the request.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.