I need to simply retrive data from server trought POST request. I can only edit front-end code. I found out that that jQuery function $.Ajax works and vanila javasript function fetch() doesn't. I figured it out that its due to PHP code doesn't echo message that i want to read but just returns it like this:
<?php
//some php logic
return array(
'result' => 'OK',
'message' => 'data I shall receive',
);
?>
Ajax request returns {result: 'OK', message: 'data I shall receive'} with following code:
this.sendFileToServer = async (file) =>{
let data = new FormData()
data.append('file', file);
let uploadUrl = this.element.getAttribute('data-uploadurl');
$.ajax({
url: uploadUrl,
body:data,
success: function (msg){
console.log(msg);
}
})
}
Javascript fetch request returns error 500 with following code:
this.sendFileToServer = async (file) =>{
let data = new FormData()
data.append('file', file);
let uploadUrl = this.element.getAttribute('data-uploadurl');
const response = await fetch(uploadUrl, {
method: 'POST',
body: data,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(response => {
console.log(response.text()); //I tried here return diffrent data like response.json(), but it doesn't work
});
}
I know i could use Ajax function when it works, but i want my code to be jQuery free. I don't understand why the fetch function doesn't work when it should be the same request. Any help how to make it work or Explanation why i can't work would be nice.