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