Reputation: 1
I am fairly new to webdev, but after one day of searching I try to get help here.
In my example I have an HTML/js page where input data is collected. This data is sent to FastAPI using POST method. In the POST method itself I evaluate the data and return a result value to the html page where it is displayed.
How it approached it:
def home(request: Request):
return templates.TemplateResponse('index.html', {'request': request})
/eval
as POST using ajaxfunction sendData(){
var data = ... // some_data
$.ajax({
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({data: data}),
dataType: "json",
url:"/eval",
})
}
/eval
/eval
redirect to new endpoint /result
which is defined as GETclass Results(BaseModel):
data: str
@app.post("/eval")
def eval(data: Results):
# Evaluate data
result = data # some evaluation happening here
# The result is not passed here to keep it simple
return RedirectResponse(url='result', status_code=303)
/result
endpoint, render the HTML/js with the result as return value using JINJA2 templates@app.get('/result')
def result(request: Request):
result = ... # some result
return templates.TemplateResponse('index.html', {'request': request, 'result': result})
I can get to 5 and also print the return value in the python console. The only thing that does not work is that the HTML/js page is rendered. It keeps showing the initial HTML/js without the result.
When I directly access the endpoint /result
I can see both the HTML and a return value.
Any ideas ? Thanks a lot
Edit: Solved I found this solution that served my purpose
Upvotes: 0
Views: 1003
Reputation: 11
If you use the same HTML/js, you can use a promise with JS, like:
fetch('../eval.php', {
method: 'POST',
body: data
})
.then(function(response) {
// Code to show results here
})
And in the php function you can return a json formated response like:
if (isset($_POST) && !empty($_POST)) {
$answer = $_POST['numberOne'] + $_POST['numberTwo'];
echo($answer);
}
If you want to use another HTML/js, you can redirect to it directly like:
header("Location: result.html?answer=". $answer);
exit();
And to get the variable you can do something like:
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const answer= urlParams.get('answer')
````
Upvotes: 1