DEV Community

Love Liberty
Love Liberty

Posted on

1

fetch() & XMLHttp errors to avoid

Sadly, I didn't avoid these errors. I hope this may help others avoid them when trying to update a webpage without completely downloading a new version. The code I ended up with seems to work:

async function fetchDbSingle(url, str) {
  const dataToSend = str;
  console.log('fetchDbSingle: ' + str);

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: dataToSend
    });

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error; // Re-throw the error to be handled by the caller
  }
}
Enter fullscreen mode Exit fullscreen mode

await works inside an async function to ensure that the data has arrived before attempting to access it. If you need to call an async function from normal code the syntax is .then:

fetchDbSingle(url, str).then(data => {
  console.log("Received data:", data);
  // Use the data here
}).catch(error => {
  console.error("Error fetching data:", error);
}); 

Enter fullscreen mode Exit fullscreen mode

If you try to access the data without using this special syntax the data will be undefined because you are accessing it before it has arrived.

If you try to access the data outside of the places marked, it will be undefined.

In my program the fetch() is calling a PHP script that reads a database.

Here are some warnings that may make no sense to the experienced, but which I wish I had known earlier:

  • Note that the PHP will send the data by echo, and that in this case the echo will not appear on the screen.
  • Make sure your PHP file only contains PHP code; no html. If it contains HTML the returned data will include all the HTML and that will be very confusing.
  • Make sure the PHP file (and any file it includes) only have one echo statement. (Oh, and check any included file for html or echo)
  • Json_encode what is to be sent by echo. You may want to have javascript json Parse it to make it a javascript array, but that isn't essential.

If anyone is interested to know why I mention the above warnings, I could write an essay on the mistakes I made & how it took me a week to correct them and you can then chuckle and feel superior.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay