user16479376
user16479376

Reputation: 1

Render HTML after Post->Redirect

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:

  1. Render HTML/js as GET using JINJA2 templates and collect data
def home(request: Request):
    return templates.TemplateResponse('index.html', {'request': request})
  1. Send collected data to endpoint /eval as POST using ajax
function sendData(){
    var data = ... // some_data    
    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({data: data}),
        dataType: "json", 
        url:"/eval",
    })
}
  1. Evaluate data and calculate result in /eval
  2. From /eval redirect to new endpoint /result which is defined as GET
class 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) 
  1. In the /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

Answers (1)

Blures.
Blures.

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

Related Questions