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);
Related
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);
});
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?
I have a problem on my code. I want to upload the image file by using formdata and ajax to the server side python program. But I got django.utils.datastructures.MultiValueDictKeyError: "'image'" error in my server uwsgi.log. I think it may not upload the image file to the server, but I don't understand what is wrong on my code.
My client code is the following.
function imageFileUploader(imageType, image) {
var credentials = {
filetype: imageType,
};
var image_file = image;
$.ajax({
url: HOST_NAME + "user/api/get_filename/",
type: 'GET',
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
jsondata = JSON.parse(data);
image_file_name = jsondata.fileurl;
// Test if the image is shown -> success
document.getElementById("previewimage").src = image
var formData = new FormData();
formData.append('filename', image_file_name);
formData.append('image', image);
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'POST',
timeout: 10000,
data: formData,
processData: false,
contentType: false,
})
.done(function (data) {
jsondata = JSON.parse(data);
alert("File upload completed...");
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
})
}
function snapPicture () {
navigator.camera.getPicture (onSuccess, onFail,
{quality: 50, destinationType: Camera.DestinationType.FILE_URI,
saveToPhotoAlbum: true});
function onSuccess (imageURI) {
var file_name = imageFileUploader("T", imageURI);
if (file_name == "") {
console.log("False");
}
else {
image_send(file_name);
}
}
function onFail (message) {
console.log("False");
}
}
And my server side code is the following.
def post(self, request, format=None):
outputLogFile("Upload Function is called...")
req_file_name = request.data['filename']
req_image = request.FILES['image']
I can get filename from the client when I comment the code of image. Please give me an advice.
I try send a binary file with jquery to node js.
This is my jquery code:
$('#addLabel').click(function(){
$.ajax({
url: "http://127.0.0.1:3030/label/66806",
type: 'PUT',
data: files,
contentType: 'application/octet-stream',
dataType: 'binary',
contentType: false,
processData: false,
success: function (data) {
console.log("sent file");
},
error: function (xhr, status, error) {
console.log("error " + status + " " + error);
}
});
});
var files;
$('input[type=file]').on('change', prepareUpload);
function prepareUpload(event)
{
files = event.target.files;
}
For example I need only show in console a data like below:
update(id, data, params) {
console.log(data);
return Promise.resolve(data);
}
Firebug show me that a data was sent but node show me only {}. Sent data are empty. What is wrong?
I have tried different ways to access header inside catch block but was not able to achieve that .
First try :
function removePaymentAccount(currenAccountDetails) {
var q = $q.defer();
$http({
url: UtilityService.createUrl(serverUrl, 'payment', 'removeMethod'),
method: 'POST',
data: currenAccountDetails
}).then(function(response) {
q.resolve(response);
})
.catch(function(err, status, headers) {
console.log(headers);
q.reject(err);
});
return q.promise;
}
Console ::
undefined
Second try :
function removePaymentAccount(currenAccountDetails) {
var q = $q.defer();
$http({
url: UtilityService.createUrl(serverUrl, 'payment', 'removeMethod'),
method: 'POST',
data: currenAccountDetails
}).then(function(response) {
q.resolve(response);
})
.catch(function(err) {
console.log(err.headers('status-msg-header'));
q.reject(err);
});
return q.promise;
}
console ::
TypeError: err.headers is not a function
at payment.api.js:72
at processQueue (angular.js:14569)
at angular.js:14585
at Scope.parent.$get.Scope.$eval (angular.js:15848)
at Scope.parent.$get.Scope.$digest (angular.js:15659)
at Scope.parent.$get.Scope.$apply (angular.js:15953)
at angular.js:16248
at completeOutstandingRequest (angular.js:5396)
at angular.js:5668
Third try:
function removePaymentAccount(currenAccountDetails) {
var q = $q.defer();
$http({
url: UtilityService.createUrl(serverUrl, 'payment', 'removeMethod'),
method: 'POST',
data: currenAccountDetails
}).then(function(response) {
q.resolve(response);
})
.catch(function(err, status, headers) {
console.log(headers('status-msg-header'));
q.reject(err);
});
return q.promise;
}
console::
same as of second
Fourth try :
function removePaymentAccount(currenAccountDetails) {
var q = $q.defer();
$http({
url: UtilityService.createUrl(serverUrl, 'payment', 'removeMethod'),
method: 'POST',
data: currenAccountDetails
}).then(function(response) {
q.resolve(response);
}, function(response) {
console.log(response.headers);
q.reject(response);
});
return q.promise;
}
console::
undefined
Fifth try:
function removePaymentAccount(currenAccountDetails) {
var q = $q.defer();
$http({
url: UtilityService.createUrl(serverUrl, 'payment', 'removeMethod'),
method: 'POST',
data: currenAccountDetails
}).then(function(response) {
q.resolve(response);
}, function(response, status, headers) {
console.log(headers);
q.reject(response);
});
return q.promise;
}
console:
undefined
i did lots of variation but unable to access (not putting up entire list). Can anyone please help me to know what i'm missing.
.catch receive a response object, this object will contains the http headers.
demo
app.factory('dataService', function($http, $q){
return {
getPayment:function(){
$http({
url: 'www.google.com',
method: 'POST',
data: [{'name':'me'}]
}).then(function(response) {
$q.resolve(response.data);
})
.catch(function(response) {
console.log(response.headers('status-msg-header'));
console.log(response.status);
$q.reject(response.statusText);
});
return $q.promise;
}
}
})
Finally got the solution.
function removePaymentAccount(currenAccountDetails) {
var q = $q.defer();
$http({
url: UtilityService.createUrl(serverUrl, 'payment', 'removeMethod'),
method: 'POST',
data: currenAccountDetails,
transformResponse: function(data) {
try {
data = JSON.parse(data);
} catch (e) {}
return data;
}
}).then(function(response) {
q.resolve(response);
},function(response) {
console.log(response.headers('status-msg-header'));
q.reject(response);
});
return q.promise;
}