Sending binary data in javascript over HTTP

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

Leave a Comment