function myFunction(username, mess_id) {
mess = document.getElementById(mess_id);
mess.innerText = "Sending...";
$.ajax({
type: 'GET',
url: '/user/resend',
data: {usr:username},
success: function(data){
mess.innerText = data;
}
})
}
In fetch API I have written as:
message = document.getElementById('mess_id');
message.innerText = 'Sending...';
fetch(url)
.then(data => data.text())
.then(mess => message.innerText = mess)
But, what about the data attribute of the ajax function.
CodePudding user response:
You can pass a body in the fetch call:
fetch(url, { body: {usr:username} })
CodePudding user response:
You're trying to send a GET request, which should hold data only in the query string, and not in the request payload.
Therefore, you can use this to send the user:
function myFunction(username, mess_id) {
mess = document.getElementById(mess_id);
mess.innerText = "Sending...";
$.ajax({
type: 'GET',
url: '/user/resend?usr=' username,
success: function(data){
mess.innerText = data;
}
})
}
However, if you still want to send data: {usr:username}
in the request body, you can send a POST request like this using fetch
:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.text(); JavaScript objects
}
postData('/user/resend', {usr:username})
.then(data => {
console.log(data);
});