AJAX to fetch, get same funcionality - javascript

i want to know how can i get the same funcionality from ajax jquery to fetch javascript
this is my ajax.
$.ajax({
url: url,
type: "POST",
data: data, //FormData
contentType: false,
processData: false,
success: function(result) {
console.log(result);
},
error(e) {
console.log(e.responseJSON.message); //<---this is what i want in my fetch :)"this is my error text"
}
});
and there my fetch
options = {
method: "POST",
body: data // FormData
}
const response = await fetch(url, options);
if(!response.ok){
return response.statusText;//always "internal server error" i need my custom msg for user ;(
}
my backend in laravel
abort(500, "this is my error text");

You have to use response.text() to get the actual response body
options = {
method: "POST",
body: data // FormData
}
const response = await fetch(url, options);
if(!response.ok){
return response.text();
}

Related

send post and get request on click using NEXT JS

i need to post and get my data when clicking on the same button [like write and show comment] , but when i click the button everything is going well but a request with 304 status code is running with infinite loop, can someone help ?
const addCommentHandler = (commentData) => {
axios({
url: `/api/comment/${eventId}`,
method: "post",
data: commentData,
headers: {
"Content-type": "application/json",
},
}).then((res) => {
const data = res.data;
console.log(data);
});
axios({
url: `/api/comment/${eventId}`,
method: "get",
}).then((res) => {
const data = res.data;
setComments(data.comments);
});
};
useEffect(() => {
addCommentHandler();
}, []);
It seems like You want to Post the Data and then want to get the Updated Comments.But you are creating Two Asynchronous Api Calls..
304 Status Code Means " The requested resource has not been modified since the last time you accessed it "
Please Refresh Cache and try Again..
const addCommentHandler = async (commentData) => {
// add Try Catch for Errors..
const responseData = await axios({
url: `/api/comment/${eventId}`,
method: "post",
data: commentData,
headers: {
"Content-type": "application/json",
},
})
const resData = await axios({
url: `/api/comment/${eventId}`,
method: "get",
})
setComments(resData.data.comments);
};
useEffect(() => {
// Pass CommentData as Params in addCommentHandler
addCommentHandler();
}, []);`

Javascript: Post data to PHP with fetch

I'm using Ajax to submit data to PHP via POST method.
I have two questions:
Is there a better way serialize data instead of doing this
const reqData = 'id= + ' myobj.id + '&name=' + myobj.name'
Please note this ^ data is an object not form data.
How can I convert the ajax call to fetch
I have tried doing it like so. It returns 200 response code. but php didn't saved the data.
async function updateCountry(url, data) {
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: data,
});
return response;
}
updateCountry('some-url', data).then(resp => console.log(resp)).catch(err => console.log(err))
here's my Ajax code:
const reqData = `id=${myobj.id}&name=${myobj.name}`;
$.ajax({
type: 'POST',
url: 'my-php-script-url',
data: reqData,
success: function (response) {
console.log(typeof response);
$('#saving-btn').hide();
if (response.includes('success')) {
$('#saved-btn').show();
setTimeout(() => {
$('#saved-btn').hide();
}, 3000);
} else {
$('#error-btn').show();
setTimeout(() => {
$('#error-btn').hide();
}, 3000);
}
},
error: function (err) {
console.log(err);
},
});
PHP doesn't support JSON parameters automatically, it requires the parameters to be either URL-encoded or FormData.
If the object keys are the same as the post parameters, you can write a loop to create the URL-encoded string:
async function updateCountry(url, data) {
const reqData = Object.entries(myobj).map(([key, value]) => key + '=' + encodeURIComponent(value)).join('&');
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: reqData,
});
return response;
}

Ajax is not sending FormData

i have a form with enctype of multipart/form-data and i am sending file (image) with FormData and ajax but as i see it is not sending. here is code
$(document).ready(()=>{
$('#form').submit((e)=>{
e.preventDefault();
const formData = new FormData();
const title = $('#title').val();
const news = $('#news').val();
formData.append('title', title);
formData.append('news', news);
formData.append('img', $('#form').find('input[type="file"] [name="thumbnail"]:first')[0].files[0]);
$.ajax({
url: '/admin-panel/add-news',
method: 'POST',
data: formData,
processData: false,
contentType: false,
success: (r)=>{
$('#news-container').html(`<div class="news">${r.news}</div>`);
},
error: (xhr,textStatus,error)=>{
try{
const response = JSON.parse(xhr.responseText);
if(response.message){
$('#error').html(`<p class="err">${response.message}</p>`);
}
}catch(error){
$('#error').html(`<p class="err">${xhr.responseText}</p>`);
}
}
})
})
})
but it gives me error
Uncaught TypeError: Cannot read property 'files'
what is problem?
Thank you!
Check your ajax property - contentType

ajax request doesn't go through in axios

So I'm using axios to be able to access Cloudinary API and upload photos. Then I want to be able to do an AJAX request that communicates with my own API to store the url for the photo I just uploaded. Here's my code:
$("#file-upload").change(function (event) {
file = event.target.files[0];
$("#add-article").click(function () {
formData.append('file', file);
formData.append('upload_preset', CLOUDINARY_UPLOAD_PRESET);
axios({
url: CLOUDINARY_URL,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: formData
}).then(function (res) {
console.log(res);
fileSource = res.data.secure_url;
$.ajax({
url: 'https://127.0.0.1:5000/api/admin/add_news',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'title': newsTitle,
'imgSrc': fileSource
}),
method: 'POST',
dataType: 'json',
crossDomain: true,
success: function (res) {
alert(res.message);
location.reload();
},
error: function () {
console.log('error')
},
complete: function (jqXHR) {
if (jqXHR.status == '401') {
console.log(jqXHR.status)
}
}
});
}).catch(function (err) {
console.log(err);
});
});
I put all of this inside a document.ready function. It returns an error like this:
I read about jQuery and JavaScript being compatible together, so what am I missing here?

How do I upload a file from Axios to Django?

I'm switching from Jquery AJAX to react-dropzone & Axios, I'd like to upload a file to my Django server, I have no issue posting a blob url of the image on the server but I want to get it under request.FILES but I am getting an empty queryset.
request.FILES : <MultiValueDict: {}> <!--- empty
request.POST : <QueryDict: {}> <!--- able to get a blob url
Here's what my axios configuration looks like :
const temporaryURL = URL.createObjectURL(step3.drop[0]);
var fd = new FormData();
fd.append('image', temporaryURL);
axios({
method: 'post',
url: SITE_DOMAIN_NAME + '/business-card/collect/',
data: fd,
headers: {
"X-CSRFToken": CSRF_TOKEN,
"content-type": "application/x-www-form-urlencoded"
}
}).then(function (response) {
console.log(response)
URL.revokeObjectURL(temporaryURL);
}).catch(function (error) {
console.log(error)
});
I am receiving the file on a classBasedView on POST request.
How can I upload the file? Where am I wrong?
Edit
I also tried "application/form-data", doesn't solve the problem
the problem came from the content-type as it was using "application/form-data" instead of "multipart/form-data".
I am answering in case, someone comes here by searching on google:
let formData = new FormData();
formData.append('myFile', file);
formData.append('otherParam', 'myValue');
axios({
method: 'post',
url: 'myUrl',
data: formData,
headers: {
'content-type': 'multipart/form-data'
}
}).then(function (response) {
// on success
}).catch(function (error) {
// on error
});

Categories