'Get rendered template in return from AJAX POST request and refresh the page (not working)

I am trying to send a post request using ajax and refresh my page with the rendered template returned from backend, It refreshes the page but it is not working like it is supposed to, The javascript is broken.

Is there any other way to do this?

Please find the simplified version of the code below:

JAVASCRIPT

$.ajax({
    url: "/post_data",
    type: 'POST',
    contentType: false,
    data: myForm,
    success: function(data){
        console.log("data posted")
        //rendered tempalte returned used to overwrite document
        document.write(data)
    }
    })

PYTHON

app.route("/")
def index(dataName=""):

    if dataName:
        #perform some changes in myTest.html
        print("dataname: ", dataName)
        
    return render_template("myTest.html")    


@app.route('/post_data',methods=["GET","POST"])
def post_data():
    myData = request.form["myDataName"]
    
    #return rendered template returned from index function
    return index(myData)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source