After attempting to use
$("html").html(this.responseText);
, I found that it successfully replaced the content but did not replace the head and body tags.
For instance, if I intended to replace the following content:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>...</script>
<script>...</script>
</head>
<body>
<h1>This is a Heading</h1>
<script>...</script>
</body>
</html>
The result when inspecting my HTML structure was as follows:
<!DOCTYPE html>
<html>
<title>Page Title</title>
<script>...</script>
<script>...</script>
<h1>This is a Heading</h1>
<script>...</script>
</html>
This caused issues with my CSS. Removing the scripts resolved the issue. Is there a solution to this problem?
I also attempted a JavaScript approach like so:
document.open();
document.write(this.responseText);
document.close();
However, this led to syntax errors with redeclaration in my JavaScripts.
The actual code where I tried to implement this is shown below:
<script>
var frm = $('#frm');
var submitActors = frm.find('input[type=submit]');
var submitActor = null;
submitActors.click(function(event) {
submitActor = this;
});
frm.unbind('submit').submit(function () {
var formAction = document.getElementById("frm").getAttribute('action'); // Get the form action.
var data = "";
var pageUrl = "";
var test_uuid = "";
var test_number = "";
var qid = JSON.parse(sessionStorage.getItem('userChoice')).qid;
if(submitActor.name == "cmdSave"){
data = {
"cmdSave" : $("#cmdSave").val(),
"Answer": document.querySelector('input[name="Answer"]:checked').value,
"csrfmiddlewaretoken": document.querySelector('input[name=csrfmiddlewaretoken').value,
"qid": qid
}
}
else if(submitActor.name == "cmdNext"){
data = {
"cmdNext": document.querySelector('#cmdNext').value,
"csrfmiddlewaretoken":document.querySelector('input[name=csrfmiddlewaretoken').value,
"qid": qid
}
}
var httpRequest = new XMLHttpRequest();
var formData = new FormData();
Object.keys(data).forEach(function(key) {
console.log(key, data[key]);
formData.append(key, data[key]);
});
console.log(formData)
httpRequest.onreadystatechange = function(){
if ( this.readyState == 4 && this.status == 200 ) {
var response = this.responseText;
console.log(this.responseText) // Display the result inside result element.
// 1.Option
{% comment %} document.open();
document.write(this.responseText);
document.close(); {% endcomment %}
// 2.Option
{% comment %} document.documentElement.innerHTML = this.responseText; {% endcomment %}
// 3.Option
$(document).ready(function(){
$("html").html(response);
});
test_number = document.getElementById("lblNrCrt").textContent;
test_uuid = "{{test.uuid}}";
pageUrl = "/intro/" + test_uuid + "/" + test_number + "/";
window.history.pushState('', '', pageUrl);
}
};
httpRequest.open("post", formAction);
httpRequest.send(formData);
return false;
});
</script>