AngularJS - Any way for $http.post to send ByteArray? - javascript

I have a byte array with some data in it. Now I want it to send the array in a RAW/Binary format to my embedded webserver:
var array = new Uint8Array(317);
... inserting data into array ...
$http.post('http://api/write_file', array)
.then(function(response) {
//Success
},function(response) {
//Fail..
});
Problem is that AngularJS by default sends the array as JSON - anyway to change this? I just want it to be transmitted raw!
EDIT:
I've tried to overwrite the transformRespons:
$http({
url: 'http://api/write_file',
method: 'POST',
transformResponse: function(value) {
return value; //Just return the value, without transform..
},
data: array
}).then(function(response) {
//Success
},function(response) {
//Fail
});
But no luck? it sends exactly the same JSON as before.

Related

POST request in JSON using $.ajax()

My backend API accepts data in JSON format, such as:
{ "article_id" = 1 }
In the front-end, I tried to add the following javascript to a button:
function articleIsSelected(id) {
let data = '{"article_id":' + id + '}';
$.ajax({
url:"https://www.myurl.com",
data: data,
type: "post",
contentType: "application/json",
success: function () {
alert("Selection succeeded!");
},
error: function () {
alert("Selection failed.");
},
});
}
It returns that the request was successful, but my database is not updated. There is something wrong with the data format. Instead of trying to hard code the data in JSON format, one should sign the value to "article_id" and then JSON encode it with JSON.stringify(data).
The data is not proper JSON, change it to:
let data = {"article_id": id};
And make sure you encode it:
JSON.stringify(data)

MVC5 Controller not receiving JSON Object

I have a controller with method as follows:
public JsonResult Save(List<BlogInfo> list)
{
return Json(new { Data = "" }, JsonRequestBehavior.AllowGet);
}
And I have an ajax post from the client as follows:
$.ajax({
url: "Home/Save",
type: "post",
contentType: "application/json",
data: ko.mapping.toJSON(ViewModel),
success: function (response) {
alert(response.Status);
}
});
My problem is that list parameter to the controller is always null. I tried changing it to string instead of List but that is also null.
Using Fiddler, I can see that the JSON is being pass as follows:
{"Data":[{"Id":1,"Title":"Sudoku Solver","Description":"Programmed Sudoku Solver","Tags":["programming","sudoku"]},{"Id":2,"Title":"Picnic","Description":"Went to millpoint","Tags":["picnic"]},{"Id":0,"Title":"Title","Description":"Description","Tags":[]}]}
The JSON you have shown doesn't represent an array, so you cannot possibly expect to bind it to a list on the server. To achieve that make sure that you are sending an array of objects from the client:
data: ko.mapping.toJSON(ViewModel.Data);
Here we take the ViewModel.Data property which represents an array so that we send only the desired JSON:
[{"Id":1,"Title":"Sudoku Solver","Description":"Programmed Sudoku Solver","Tags":["programming","sudoku"]},{"Id":2,"Title":"Picnic","Description":‌​"Went to millpoint","Tags":["picnic"]},{"Id":0,"Title":"Title","Description":"Description‌​","Tags":[]}]

AngularJS - Posting data to API is not working

I am trying to send data that a user puts into a textarea and text input to and API that will save the data.
Here is the function:
$scope.forward = function() {
$http({
url: 'http://appsdev.pccportal.com:8080/ecar/api/reject/' + carID,
method: "POST",
data: "comments=" + this.comments,
data: "recipient=" + this.recipient,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
then(function(response) {
$scope.output = response.data;
})
}
What it does when it is run is it logs only the recipient and not the comments. I am guessing because I am using "data" twice and it is only recognizing the last one (in this case "recipient"). How can I pass 2 values through this to the API.
Thanks
As you said, you're overwriting the data key from the plain object you're passing to $http, send it all together:
data: { recipient: this.recipient, comments: this.comments }
pass it as an object:
data : {comments: this.comments, recipient: this recipient}
This got it working just fine:
data: 'recipient='+encodeURIComponent(this.recipient)+'&comments='+encodeURIComponent(this.comments),

My Json get cut off when sent with Ajax

I'm using angular to save new data on the database, I take the data from my inputs, put it in a object and I convert it to a Json, I send it by POST, but my JSON gets cut off and I have no clue why is it happening.
var myJson = angular.toJson(myObject);
$http({
method: 'POST',
url: 'http://url/file.php',
data: {
'data': myJson
}
})
.success(function (data){
console.log(data);
})
My file.php has a var_dump($_POST) in it, and it shows that:
[
{
"uuid":"56456456456456456456465456"
},
{
"store_name":"",
"store_email":"",
"store_facebook":"",
"contact_name":"John Doe",
"contact_email":"email#email.com",
"contact_facebook":"http://localho
Angular's http post method sends whatever data it is passed to. You should check your generated json data after
var myJson = angular.toJson(myObject); using console.log(myJson);
and that itself must be cut off.

Issue with JSON.stringify adding a extra \ and "" to my Json object

Hi I am creating using Javascript an array of object with a key and a value using the following code.
ValuesArray.push({ key: $(this).attr('someattribute'), value: $(this).val() });
As a result I have am array of object like this:
key:29; value: 'Country'
Key:12; value: '4,3,5'
when I am trying to stringify it and send that JSON in a post I am having a wrong formatted JSON with \ and " in places that I dont want so when I try to desirales that JSON as a JObject on codebehind with C# I am having trouble. How can I create a clean JSON using the stringify
var jObject = JSON.stringify(ValuesArray);
My JSON now which is wrong is:
{
"JObject": "[{\"key\":\"29\",\"value\":\"Country\"}, {\"key\":\"30\",\"value\":\"4,3,5\"}]"
}
I would like to have a JSON object like this
{
"JObject": [{"key":"29","value":"Country"},{"key":"30","value":"4,3,5"}]
}
without the quotes around the [] and the character \
Any good idea to solve it.
Thank you
More detail this how I am sending the JSON to my API
this is how I am sending the JSON to my Web API:
function PostAPIRequest(address) {
var jObject = JSON.stringify(ValuesArray);
var responseJson = null;
$.ajax({
url: address,
type: 'POST',
dataType: 'json',
data: { JObject: jObject },
success: function (data) {
responseJson = data
ProcessDataResponse(responseJson);
//TODO: REFRESH THE DATA GRID
},
error: function (xhr, ajaxOptions, thrownError) {
//TODO redirect to the error page and send error email there.
alert(xhr.status);
alert(thrownError);
}
})
}
and this how I am receiving it in my API controller
...
// POST api/datavalues/5
public string Post(int id, JObject value)
{
var temp = value;
...
It looks like you are placing a string as the value in your map. You should do something like:
var objMap = {"JObject" : ValuesArray};
var json = JSON.stringify(objMap)
What's happening is you are double json encoding your values array - note that your "invalid" JSON value is actually a JSON string rather than the array that you want.
EDIT
It looks like you are sticking in JSON strings of maps into an Array and then stringifying that. Here's a jsfiddle that should help you get what you are looking for - http://jsfiddle.net/4G5nF/
In your post request, try this
var jObject = {"JObject" : ValuesArray};
$.ajax({ url: address,
type: 'POST',
dataType: 'json',
data: jObject,
success: function (data) { .. }});
Note the change in the data attribute. That is a value that is automatically JSONified for you.
const config = {a: 1, b: 2}
console.log(JSON.stringify(JSON.stringify(config)))
"{\"a\": 1, \"b\": 2}"
May be you have an old prototype library.
As I remove it, bug has disappeared

Categories