Search code examples
javascripthtmlpython-3.xjinja2fastapi

Unable to make Request to FastAPI server using javascript


I have Created a fastapi python server which has two endpoints. Both of them renders different html templates. But 1st template is Successfully Rendered and 2nd is also successfully rendered when submit button is clicked. But when back button on 2nd template is clicked then 1st template is not rendered

FastAPI Server :-

from fastapi import FastAPI , Request , Response
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel

app = FastAPI()
templetes = Jinja2Templates(directory="templetes")

@app.get("/test")
async def test(request : Request):
    data = {
        "name" : "John",
        "dob" : "31-3-230"
    }
    return templetes.TemplateResponse("result.html" , {"request" : request , "data":data})

class InputData(BaseModel):
    name : str
    date : str

@app.post("/result")
async def get_result(request : Request , input : InputData):
    data = {
        "name" : input.name,
        "dob" : input.date
    }
    print(data)
    return templetes.TemplateResponse("result.html" , {"request" : request , "data":data})

@app.get("/")
async def root(request : Request):
    return templetes.TemplateResponse("form.html" , {"request" : request})

1st Templete - Form.html :

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Entry Form</title>
</head>

<body> <input id="first" type="text"> <input id="dob" type="date"> <button type="button"
        onclick="submit()">Submit</button>
    <script>function submit() { const name = document.getElementById("first").value; console.log(name) const date = document.getElementById("dob").value; console.log(date) fetch("/result", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: name, date: date }) }).then(response => response.text()).then(html => { document.getElementsByTagName("html")[0].innerHTML = html console.log(html); }) }</script>
    <div id="result"></div>
</body>

</html>

2nd template - result.html :

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Result</title>
</head>

<body>
    <p>Your Name is :{{data.name}}</p>
    <p>Your Date of Birth is :{{data.dob}}</p>
    <script>function displayHTML() { console.log("hello"); fetch("/", { method: "GET" }).then(response => response.text()).then(html => { document.getElementsByTagName("html")[0].innerHTML = html; }); } window.displayHTML = displayHTML; </script>
    <button onclick="displayHTML()">Back</button>
</body>

</html>

I want to show 2nd page in the same window of browser in place of 1st on submit button and 1st in place of 2nd on click of back button.

Could anybody help me on this!


Solution

  • I found the mistake, I have not added javascript code to a separate js file and placed in static folder. After adding js code to seprate file amd link that file to templates and server, everything is working fine