Home > Backend Development > PHP Tutorial > fetch() & XMLHttp errors to avoid

fetch() & XMLHttp errors to avoid

Susan Sarandon
Release: 2024-11-26 13:27:11
Original
272 people have browsed it

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
  }
}
Copy after login

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);
}); 

Copy after login

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.

The above is the detailed content of fetch() & XMLHttp errors to avoid. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template