Sending binary data in javascript over HTTP - javascript

I'm trying to send a HTTP POST to a device on my network. I want to send four specific bytes of data to the device unfortunately I only seem to be able to send strings to the device. Is there anyway to send raw binary using javascript?
Here's the script I'm using to do the POST, it currently doesn't run unless I put a string in the data field. Any ideas?
(function ($) {
$.ajax({
url: '<IP of Address>',
type: 'POST',
contentType: 'application/octet-stream',
//data:'253,0,128,1',
data:0xFD008001,
crossDomain: true
});
})(jQuery);

By default, jQuery serializes the data (passed in data property) - and it means 0xFD008001 number gets passed to the server as '4244668417' string (10 bytes, not 4), that's why the server treats it not as expected.
It's necessary to prevent such behaviour by setting $.ajax property processData to false:
By default, data passed in to the data option as an object
(technically, anything other than a string) will be processed and
transformed into a query string, fitting to the default content-type
"application/x-www-form-urlencoded". If you want to send a
DOMDocument, or other non-processed data, set this option to false.
... but that's only part of the whole story: XMLHttpRequest.send implementation has its own restrictions. That's why your best bet, I suppose, is to make your own serializer using TypedArrays:
// Since we deal with Firefox and Chrome only
var bytesToSend = [253, 0, 128, 1],
bytesArray = new Uint8Array(bytesToSend);
$.ajax({
url: '%your_service_url%',
type: 'POST',
contentType: 'application/octet-stream',
data: bytesArray,
processData: false
});
Or without using jQuery at all:
var bytesToSend = [253, 0, 128, 1],
bytesArray = new Uint8Array(bytesToSend);
var xhr = new XMLHttpRequest();
xhr.open('POST', '%your_service_url%');
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.send(bytesArray);

You can send binary data via ajax with xhr2, you can send the data as a typed array or a blob.
(function ($) {
var data = new Uint32Array(1);
data[0] = 0xFD008001;
$.ajax({
url: '<IP of Address>',
type: 'POST',
contentType: false,
processData: false,
//data:'253,0,128,1',
data:data,
crossDomain: true
});
})(jQuery);
https://developer.mozilla.org/en-US/docs/Web/API/Uint32Array

You can convert your data with type of ArrayBuffer to a ArrayBufferView like this:
var fileContent = new DataView(<ArrayBuffer_data>);
With this you wont get a warning in the console when sending fileContent.

You could use atob() and btoa():
var data = new Uint32Array(1);
data[0] = 0xFD008001;
atob(data)
This converts your binary data into a base64 string that can be sent as text.

Related

Sending JavaScript Object through AJAX works, JSON doesn't?

I'm trying to send data through AJAX and most places I read online say I need to send it as JSON. However, If I try to send it as JavaScript Object it actually works, wheres if I try to send it as JSON it gives me a CORS error (but that's another topic: here's a link to the issue: API Gateway CORS: no 'Access-Control-Allow-Origin' header (NON-PROXY)).
I guess my question is, is it perfectly fine for me to send the data as JavaScript object as oppose to JSON? is there a benefit of doing one over the other?
Example:
This works: (Sending data as JS Object):
$("#xform").submit(function (event) {
event.preventDefault();
var obj = { xnumber: 1 };
$.ajax({
type: 'GET',
url: 'adddresshere',
data: obj,
dataType: 'json',
contentType: 'application/json',
}).done(function (result) {
table.clear();
table.rows.add(result).draw();
});
});
This doesn't work - (sending data as JSON)
$("#xform").submit(function (event) {
event.preventDefault();
var obj = { xnumber: 1 };
var myJSON = JSON.stringify(obj);
$.ajax({
type: 'GET',
url: 'adddresshere',
data: myJSON,
dataType: 'json',
contentType: 'application/json',
}).done(function (result) {
table.clear();
table.rows.add(result).draw();
});
});
So can I just stick with sending JS object from now on as long as it works (like it does for me right now)?
Short Answer is Yes.
Explanation:
When the online blogs says that you need to pass JSON objects - They mean you need to send Java Script Object Notation objects. When you write it like:
var obj = { xnumber: 1 }
You are already creating a JSON object. This is good to send via ajax call. When you do a JSON stringify operation, it basically converts the above JSON into string. Hence, the server is unable to treat as JSON object and it will fail.
Your JavaScript Object is deserialized JSON. As Heretic Monkey pointed out, JSON.stringify serializes your JavaScript Object to be sent over the wire.

Why does node.js attach a string value in my array to another object in the array as true?

I'm not sure why this is happening, but could use some input.
I have an object attached to the body of a POST request through jquery ajax. The object is similar to this example:
var dogData = {breeds: [{Dog: "Golden Retriever"}, "Rottweiler"]}
The AJAX request is this:
$.ajax({
type: "POST",
url: "api/dog",
data: dogData,
})
On my server using Express + bodyparser:
app.post('/dogs', function(req, res){console.log(req.body)})
When I console.log the object:
{breeds: [{Dog: "Golden Retriever", Rottweiler: true}]}
I want the same object that I initially started out with to be returned from the server. Can someone explain why the string is attached to the previous object along with a boolean value?
use jsonparser on your server and make your post with json content
$.ajax({
type: "POST",
url: "api/dog",
data: JSON.stringify(dogData),
contentType: 'application/json; charset=utf-8'
})
Body parser parses urlencoded form data.
When you send your data it will be converted to:
breeds[0][Dog]=Golden+Retriever&breeds[Rottweiler];
When bodyparser parse it, because of there is no value on Rottweiler and it exists, it will be converted to "true"

AJAX call to ASP.NET web method returns garbage characters at end of content, but only in Chrome

This is my call:
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: location,
data: JSON.stringify(ajaxData),
dataType: 'xml',
success: callback,
error: function (x) { alert(JSON.stringify(x)) }
});
The method is defined in an .aspx.vb file:
<Web.Services.WebMethod(EnableSession:=True)>
<Script.Services.ScriptMethod(ResponseFormat:=Script.Services.ResponseFormat.Xml)>
Public Shared Function WebMethod(ByVal arg As String) As String
Dim xml As New Text.StringBuilder
Using writer As XmlWriter = XmlWriter.Create(xml, New XmlWriterSettings With {.Encoding = New Text.UTF8Encoding(False)})
'build XML and return it
End Using
End Function
This works as imagined in IE and Firefox, but in Chrome the error handler fires, and the responseText property of the request object contains the expected XML plus a varying number of \u0000s. I assume I'm messing up the encoding somehow, but I can't figure out how. This is what the end of response looks like in the Chrome visualiser:
Seems like there is some Encoding difference, the data may be encoding differently by the server with respect to browser. Check the headers for the incoming AJAX.
Try this, set Response.CharSet = "iso-8859-1" at server.
or Response.CharSet = "iso-8859-13" at server.
Take a look at this blog:Charset Encoding in ASP.NET Response

Post JSON string made from JavaScript array to server with jQuery [duplicate]

Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

How to send JSON instead of a query string with $.ajax?

Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

Categories

Resources