I've implemented a simple JavaScript function that handles fetching a URL and updating the HTML page upon receiving a response. Here's an example of how it works:
function postToDatabase(self) {
// other code here
async function postData() {
const url = "fetchnewseq"
const response = await fetch(url, {
method: 'POST',
headers: {
'X-CSRFToken': csrftoken,
'Content-Type': 'application/json'
},
body: JSON.stringify(commandsJSON)
});
return await response.json()
}
postData().then((data) => {
window.location.replace(data.url);
});
}
The postToDatabase function is called by a button like this:
<button onclick="postToDatabase(this)" class="btn btn-success">Confirm</button>
In the backend, I'm using Django and the corresponding view for the URL handling looks like this:
def fetch_new_seq(request):
received_json = json.loads(request.body.decode("utf-8"))
print(received_json)
messages.success(request, "Received")
redirect_url = reverse('newSeq')
return JsonResponse({'url': redirect_url})
However, there seems to be an issue where the fetch operation is being triggered twice with identical results, even though the button should only be clicked once.
Additionally, the console in Mozilla Browser is showing an error message Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
The button triggering the postToDatabase function is nested within several div elements:
<div id="container" class="container-fluid">
<div class="container text-center">
<h3>Creating motion sequences</h3>
<input
type="text"
class="form-control mt-3 mb-3"
id="titleseq"
placeholder="Insert Title"
/>
<div class="row">
<div class="d-grid gap-2 col">
<button onclick="loadJS()" class="btn btn-secondary">
Reorder
</button>
</div>
<div class="d-grid gap-2 col">
{% csrf_token %}
<button onclick="postToDatabase()" class="btn btn-success">
Confirm
</button>
</div>
<div class="d-grid gap-2 col">
<button onclick="addNewRow()" class="btn btn-primary">
Add Movement
</button>
</div>
</div>
</div>