DEV Community

Love Liberty
Love Liberty

Posted on

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.

Top comments (0)