Twice the fetch is triggered

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>

Answer №1

It seems like I've identified the issue. The situation arose from having the async function containing the fetch code nested within a for loop as shown below:

for (var i = 0; i < len_array; i++) {
  if (
    comandi_json["lista_comandi"][i]["comando"] == "" ||
    comandi_json["lista_comandi"][i]["tempo"] == null
  ) {
    console.log("Error");
    return;
  } else {
    async function postData() {
      const url = "fetchnewseq";

      const response = await fetch(url, {
        method: "POST",
        headers: {
          "X-CSRFToken": csrftoken,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(comandi_json),
      });
      return await response.json();
    }
    postData().then((data) => {
      window.location.replace(data.url);
    });
  }
}

Upon closer inspection, it became evident that each time the first check passed without encountering a return, the else block executed and resulted in the fetch function being triggered multiple times, causing the problem.

The solution was to reorganize the structure by moving the relevant code outside of the for loop, which effectively resolved the issue:

for (var i = 0; i < len_array; i++) {
  if (
    comandi_json["lista_comandi"][i]["comando"] == "" ||
    comandi_json["lista_comandi"][i]["tempo"] == null
  ) {
    console.log("Error");
    return;
  } 
 }

    async function postData() {
      const url = "fetchnewseq";

      const response = await fetch(url, {
        method: "POST",
        headers: {
          "X-CSRFToken": csrftoken,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(comandi_json),
      });
      return await response.json();
    }
    postData().then((data) => {
      window.location.replace(data.url);
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to create a translucent glass floating box over HTML elements, similar to the frosted glass effect seen in iOS7?

Creating an overlapping div with a frosted glass effect typically requires using an image background (like ). I am interested in having a floating div (position:fixed) that can apply a frosted glass effect over any content below it, whether it be an image ...

Issue with sending array as parameter in ajax call in Laravel

I am currently encountering an issue while attempting to pass an array through an AJAX request. <input type="text" name="item_name[]"> <input type="text" name="address"> $(document).on('click', '#save_info', function () { ...

Refresh the block's content seamlessly without the need for a page reload

Within the index.html page There exists a block called content that contains various content blocks. An additional navigation menu with numerous links is present. It is important that when you click on a menu link, the content within the content block re ...

Is it possible to automatically update HTML database information in Django using Ajax?

I am currently working with a Django server that is locally hosted and is used to display sensor data retrieved from a MySQL database. The data is presented on the instruments.html page using variables like {{qs.value}} obtained from various files such as ...

Execute a function using a click event within a statement

Is it possible to trigger a function with parameters based on the result of a statement? For example, can we achieve something like this: (click)="datavalue.elementDataCollection.length > 1 ? AddNewDialog (datavalue,datavalue.COCLabel,mainindex,i) : r ...

What is preventing the data property from updating in setInterval?

Looking for a way to increase the speed of the props while my marker is moving? Currently, the speed only updates when the pause button is clicked. How can I automatically update this.speed when clicking the speed button? I have defined the speed prop in ...

Exploring Next.js' dynamic routes with an alternative URL approach

Currently in the process of transitioning a React project to Next.js, I've encountered a minor issue with Dynamic Routing that doesn't seem to have any readily available solutions online. I have multiple information pages that utilize the same c ...

Accessed a property that is not defined on the instance during rendering

One of the components I'm working on displays data that is defined in the component's state. To access this data, I created a getter: export default createStore({ state: { foo: true, }, getters: { getFoo: state => state.fo ...

AngularJS: Issue with Variable Value Rendering

I recently started working with Angular. In my JavaScript file, I have the following code: App.controller('ProductController', ['$scope', 'ProductService', function ($scope, ProductService) { console.clear(); console. ...

Is there a way in JavaScript to convert a web page into a string?

I'm looking for a way to retrieve the HTML content of a webpage using JavaScript, even if it's on a different domain. Similar to what wget does but in JavaScript. I intend to use this for web crawling purposes. Could anyone guide me on how to fe ...

Dragging elements with jQueryUI multiple times

Is there a way to configure drag and drop functionality so that one element can be dragged multiple times? I attempted to create something similar to this http://jsfiddle.net/28SMv/3/, but after dragging an item from red to blue, the element loses its abi ...

Ways to extract innerHTML content from a loaded element generated by using the .load() method

Check out the code snippet below: template.html : <div id="nav"> Welcome to Space </div> layout.html : <div id="content"> </div> $('#content').load("template.html #nav"); ale ...

Can Cell be rendered into a targeted element?

Can a Cell from CellJS be rendered into a specific HTML element? For example, including a Cell alongside some static HTML that is not managed by cell. Or having two separate Cell apps on a single page. <!DOCTYPE html> <html> <header> ...

Updating all the direct components within the corresponding category with jQuery

Here is the HTML content I am working with: <li class="info"> info<li> <li class="other"> info<li> <li class="other"> info<li> <li class="Error"> error<li> <li class="other"> error<li> < ...

Looking to set an object value as optional in JavaScript?

Hello, I am currently in the process of developing a web application using ReactJS with Auth0 for user authentication. In order to update user information on my backend, I am utilizing state to store the necessary data. My challenge lies in allowing eith ...

How can I extract the width of an uploaded image and verify it using JavaScript?

Is it possible to retrieve the image width through upload using PHP and then validate it in JavaScript? $_FILES['image'] If the image size is not equal to 560px, can we return false and display an alert message using JavaScript? Also, I am won ...

Having difficulty adding a Dropdown Menu in a Pop-up Box

I am trying to incorporate a select menu inside of a popover, but every time I attempt to do so, the popover content block remains blank. The popover is associated with a side menu item called "Date History". Below is the code snippet I am using to constr ...

Establish a connection to an SSH server using Node.js code, specifying the SSH key and server hostname for

Having VPN access allows me to SSH into the server using the following command in the terminal: ssh qa-trinath01.my-qa This command works perfectly fine when executed from the terminal. However, when attempting to connect via Node.js, I encounter issues ...

Changing the color of a text box when it is disabled can be achieved through JavaScript

I'm facing an issue with the formatting of my HTML elements. Specifically, I have 2 combo boxes and one text box in which all 3 are disabled. However, when they are disabled, the background color of the text box does not match that of the combo boxes. ...

The optional attribute feature in Angular directives

Looking for a solution: angular .module('test') .directive('multiButton', function () { return { restrict: 'E', replace: true, scope: { disabled: '@' }, template: ' ...