How to get a binary data in feathers services? - javascript

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?

Related

How to access data from ajax result (json object) using jquery

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);
});

How can I upload the image file by using formdata

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.

Ajax JSON empty passing

To all whom it may concern (I am really just trying to reach the "please add more detail" limit)
When passing data to the server as below the body is shown as empty.
Server
// POST method route
app.post('/pass', function (req, res) {
console.log("server received POST from homepage")
console.log(req.body)
res.send('POST request to the homepage')
})
Client
function ajaxJSONFunc(){
var inputData = document.getElementById('input2').value
var json = {"data":"abc"};
$.ajax({
url: "/pass",
type: "POST",
data: json
contentType: "application/json",
// dataType: "json", only use if you need to responce data to be JSON, if its not JSON an error will fire when uncommented. defaults to text
success: function(data) {
console.log("data passed back from server is:" + data)
},
error: function(err) {
console.log("an error occured")
console.log(err)
}
})
}
Works when passing like this (below), but I would prefer to send JSON data and not strings
$.ajax({
url: "/pass",
type: "POST",
data: inputData,
contentType: "application/x-www-form-urlencoded",
//dataType: "json", only use if you need to responce data to be JSON, if its not JSON an error will fire when uncommented. defaults to text
success: function(data) {
console.log("data passed back from server is:" + data)
},
error: function(err) {
console.log("an error occured")
console.log(err)
}
})
You defined contentType: "application/json". That's means you have to send a json object.
You have to use JSON.stringify() method.
data: JSON.stringify(json)
JSON.stringify function turns a Javascript object into JSON text and stores it in a string.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var json = "abc";
$.ajax({
url: "/pass",
type: "POST",
data: json,
contentType: "application/json",
// dataType: "json", only use if you need to responce data to be JSON, if its not JSON an error will fire when uncommented. defaults to text
success: function(data) {
console.log("data passed back from server is:" + data)
},
error: function(err) {
console.log("an error occured")
console.log(err)
}
});
});
</script>
</head>
<body>
</body>
</html>

How do I get jqxhr.responseText from HttpResponseMessage?

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);

JSON data 400 Bad request Error

I have JSON data sending to server. When I submit the for it is printing the data in console but not sending to the server.
It gives the following error
POST http://localhost:8080/rest/review/createReview 400 (Bad Request)
Here is my code
var promise = jQuery.ajax({
url: 'http://localhost:8080/rest/review/createReview',
type: 'POST',
data: '{myReview: myReview}',
dataType: "text",
contentType: "application/json",
success: function (data) {
console.log("Request successful", data);
},
error: function (data) {
console.log("Request failed", data);
}
});
It may be that your data is not valid JSON. Try:
data: JSON.stringify({myReview: myReview})

Categories