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?
Related
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();
}
I want to return the ajax returned value in back to my function where it was called but no data was returned.
function payment {
var x = payment_status(status)
}
function payment_status (status)
{
return $.ajax({
url: "http://127.0.0.1:81/public/api/payment_status",
type: 'POST',
'content-type':'application/X-WWW-form-urlencoded',
'Accept': 'application/json',
data: {
'status' : status,
}, success: function(response){}
});
}
$.ajax() returns a thenable or a Promise (in jquery 3+) See https://www.promisejs.org/ or Promise on MDN (or maybe this answer)
So you can use an async function (but maybe transpile it with babel):
async function payment() {
try {
var response = await payment_status(status);
} catch (error) {
// Handle error
}
}
function payment_status(status) {
return $.ajax({
url: "http://127.0.0.1:81/public/api/payment_status",
type: "POST",
"content-type": "application/X-WWW-form-urlencoded",
Accept: "application/json",
data: {
status: status
});
}
So I have this function that gets the user details via UUID;
function getUserDetails(uuid){
$.ajax({
url:'http://localhost/hrms/controller/php/getUserDetails.php',
method: 'POST',
dataType: 'json',
data: { uuid: uuid },
success:function(result){
console.log(result);
},
error: function(xhr, status, error){
if(xhr.status == 401){
toastr.error(xhr.responseText);
}
}
});
}
which give me the result of
AJAX RESULT
Now I wonder how to access that data. The function is from different js page. How can I throw the json result to another js page?
Im using JQUERY. Thanks and more powers.
When you use ajax it takes some time to return the data form server to client, so you can use promise or callbacks:
Callbacks:
function.js
function getUserDetails(uuid, callback){
$.ajax({
url:'http://localhost/hrms/controller/php/getUserDetails.php',
method: 'POST',
dataType: 'json',
data: { uuid: uuid },
success:function(result){
callback(result);
},
error: function(xhr, status, error){
if(xhr.status == 401){
toastr.error(xhr.responseText);
}
}
});
}
index.js
getUserDetails(uuid, function(data){
console.log(data);
});
Promises
function.js
function getUserDetails(uuid){
return new Promise((resolve, reject) => {
$.ajax({
url:'http://localhost/hrms/controller/php/getUserDetails.php',
method: 'POST',
dataType: 'json',
data: { uuid: uuid },
success:function(result){
resolve(result);
},
error: function(xhr, status, error){
if(xhr.status == 401){
toastr.error(xhr.responseText);
}
const reason = new Error('Error');
reject(reason);
}
});
});
}
index.js
getUserDetails(uuid).then(function(data){
console.log(data);
});
I just started working with .net and I can give complete webapi endpoint urls to make AJAX calls or give relative url. How does client project know where to locate webapi endpoints when using relative URL ?
Client AJAX current call:
$.ajax({
url: localhost:3227/api/form/post,
contentType: "application/json; charset=UTF-8",
type: "POST",
dataType: "json",
data: JSON.stringify(formData),
success: function (resp) {
console.log("Updated successfully!"); },
error: function (request, status, error) {
console.log(request.responseText + ' Error:' + error.message);
}
});
What I want to do:
$.ajax({
url: /api/form/post,
contentType: "application/json; charset=UTF-8",
type: "POST",
dataType: "json",
data: JSON.stringify(formData),
success: function (resp) {
console.log("Updated successfully!"); },
error: function (request, status, error) {
console.log(request.responseText + ' Error:' + error.message);
}
});
How does AJAX call know where localhost:3227/api/form/post is if I remove localhost:3227 and only keep /api/form/post
Is it in some project configuration that I don't know about ?
In config file add,
var api_url = localhost:3227;
and then,
$.ajax({
url: api_url+ '/api/form/post',
contentType: "application/json; charset=UTF-8",
type: "POST",
dataType: "json",
data: JSON.stringify(formData),
success: function (resp) {
console.log("Updated successfully!"); },
error: function (request, status, error) {
console.log(request.responseText + ' Error:' + error.message);
}
});
This is my server side code
var response = new HttpResponseMessage
{
Content = new StringContent("FAIL FAIL"),
StatusCode = HttpStatusCode.InternalServerError,
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return Task<HttpResponseMessage>.Factory.StartNew(() => response);
This is my client side code using jquery
$.ajax({
type: 'POST',
url: 'someurl',
data: somevalues,
success: function (data) {
console.log(data);
},
error: function (jqxhr) {
console.log(jqxhr);
}
});
But when I check using firebug, my jqxhr.responseText is "".
How do I retrieve "FAIL FAIL"?
Try like this:
var ajaxReult = $.ajax({
type: 'POST',
url: 'someurl',
data: somevalues,
success: function (data) {
// console.log(data);
},
error: function (jqxhr) {
// console.log(jqxhr);
}
}).responseText;
console.log(ajaxReult);