I want to display the binary code of a music file. But somehow the code below doesn't seem to work. Any suggestions??
function binary() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","1.wav",true);
xmlhttp.overrideMimeType("text/plain; charset=x-user-defined");
xmlhttp.onreadystatechange = function(buffer) {
var binaryCode = "";
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var binStr = this.responseText;
for (var i=0; i<binStr.length; i++) {
var byte = binStr.charCodeAt(i) & 0xff; // get byte at i
binaryCode += byte;
}
}
document.getElementById("result").innerHTML = binaryCode; // should display binary code
};
xmlhttp.send();
}
Not all byte values are expressible in a string and will not appear or cause the string to cut off short.
XMLHttpResponse.ResponseText/ResponseXML will return the http response content as a string. Any byte values of 0 for example will terminate the string.
Have the server return a Base64 representation of the bytes and decode into byte values on the client side.
Your code seems to be working fine on my chrome browser.
What is exactly the problem your are experimenting ?
You may want to display the binary in an hexadecimal form by doing something like:
binaryCode += '0x' + byte.toString(16) + ' '
edit:
this jsfiddle works on my chrome:
http://jsfiddle.net/e6Kfk/
However, i do not think that this method is crossbrowser, especially if you want to deal with ie (haven't tested it though)
Related
I was looking to implement the front end functionality to download set of videos using java script. There are bunch of processes that run on the downloaded videos. Currently I am using XmlHttpRequest that can only start processing the bytes after downloading the entire video. Below is the sample code. I have taken any http request for problem statement. Processing starts in "xmlhttp.readyState==4" block.
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.thomas-bayer.com/sqlrest/CUSTOMER/1",true);
xmlhttp.send();
}
I was trying to find out if there is any way to download the response in chunks and start processing it while it is getting downloaded. This is something similar to what we can do using java.io.Inputstream package. Please see a code below which reads byte by byte with a chunk size as 1 byte.
try {
URL url = new URL("http://www.thomas-bayer.com/sqlrest/CUSTOMER/1");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
InputStream is = conn.getInputStream();
byte buff[] = new byte[1];
int readData = 0;
StringBuilder response = new StringBuilder();
while (true) {
readData = is.read(buff);
if (readData == -1)
break;
response.append(new String(buff, 0, readData));
}
is.close();
conn.disconnect();
System.out.println(response);
} catch (MalformedURLException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
Please suggest. Thanks for your help in advance.
I wonder if there is any simple way to get request processing percent with ajax.(not jQuery)
I tried some way to get this percent on my own.
in my php file I Set response content-length.
and then I use this code for progress percent:
function ajaxPost(url,data,callBack,progress)
{
var postPar = data;
//for(var f in data) postPar += f+'='+data[f]+'&';
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
var percent = 0;
if(xmlhttp.readyState>=3) percent = Math.ceil(xmlhttp.responseText.length*100/xmlhttp.getResponseHeader('Content-length'));
progress(percent);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
callBack(xmlhttp.responseText);
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(postPar);
}
but there is some problems:
1- I cant use this function for another site except this.(because other sites may not have content-length header)
2- this code is not working with upload requests.
Now I want to know is there any way to improve this or maybe some better way to do ?
thanks in advance...
I have an application that has a long time processing in code behind.
I was thinking on starting the long time processing by calling from javascript a page,
function OnCopy(type){
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//window.clearInterval(interval_handler);
alert('done');
}
}
xmlhttp.open("GET", "<%=Request.Path %>?copy=" + type, true);
xmlhttp.send();
interval_handler = window.setInterval(OnCheckStatus, 1000);
}
The last line of this function will start a timer, to check every second the status:
function OnCheckStatus(){
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//window.clearInterval(interval_handler);
//var result = eval(xmlhttp.responseText);
//var pb = document.getElementById('progressbar_' + result[0]);
//if(pb != null)
// pb.innerHTML = result[1] + ' % - ' + result[2];
debug++;
var pb = document.getElementById('progressbar_test');
pb.innerHTML = debug;
}
}
xmlhttp.open("GET", "<%=Request.Path %>?checkstatus=1", true);
xmlhttp.send();
}
On code behind I have this long time processing function and check status function:
private void Copy(string type)
{
Application["ProgressBar.Type"] = type;
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(100);
Application["ProgressBar.Value"] = i.ToString();
}
Application["ProgressBar.Type"] = null;
Application["ProgressBar.Value"] = null;
}
private void CheckStatus()
{
Response.Clear();
string type = (string)Application["ProgressBar.Type"];
string value = (string)Application["ProgressBar.Value"];
if (type == null) type = "";
if (value == null) value = "";
string response = "['" + type + "','" + value + "','" + DateTime.Now.ToString("HH:mm:ss") + "']";
Response.Write(response);
Response.End();
}
Now, the problem is that until the Copy function is not finished, there is no answer on the CheckStatus function from code behind (I think all calls are queued), but, when is finished, the displayed debug value is starting from 10, directly, like all the answers for these 10 calls are coming at the same time.
Is like ASP.NET is only responding to one call only at a time, from the browser. I was having the impression that the server will process at least 2 calls at the same time from the same browser.
Can you help me with this, please?
Please check this article. I think that it will help you with your issue.
But also there is an integrated solution in asp.net webforms named as UpdateProgress msdn link with example
I imagine at some point my familiarity with PHP is making me write something incorrectly, but I've been reading up and can't seem to find a way to achieve what the below is intended to achieve. In the end, I should have a multidimensional array like such:
cardArray[#]
'uniqueID' => "#";
'cardName' => "blahblah";
'series' => "blahblah";
(Where the #s are actual numbers, of course.) The string that is returned via AJAX is formatted such that each set of 3 is delimited by a colon and within each set each item is delimited by a pipe. (The final line I just threw in as a test to see if ANYTHING was getting stored.)
Here's the code:
function buildCardList() {
var returnedString;
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
returnedString = xmlhttp.responseText;
}
}
xmlhttp.open("POST","test02.php",true);
xmlhttp.send();
var cardArray = new Array();
cardArray = returnedString.split(":");
for (var i = 0; i < cardArray.length; i++) {
var tempVar = cardArray[i];
var tempArr = tempVar.split("|");
cardArray[i] = {
"uniqueID" : tempArr[0],
"cardName" : tempArr[1],
"series" : tempArr[2]
};
}
document.getElementById("test").innerHTML = cardArray[0]['uniqueID'] + "<br>" + cardArray[0]['cardName'] + "<br>" + cardArray[0]['series'] + "<br><br>";
}
I am busy developing a chrome extension.
What it will do:
Get data from a PHP page (XMLHttpRequest)
Split the result variable using .split
And when someone clicks on a div, it will call a function to insert a css file with that name I got in number 1.
My problem:
Well nothing happens when I click that button. It works when I used the variable, "newvar", instead of the variable, "currenttheme" from the XMLHttpRequest. I tried converting it to a string as well using .toString. Oh, alerting the variable does work and gives exactly the same response as newvar.
My code: (Sigh!)
//My XMLHttpRequest
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
user_data = xmlhttp.responseText;
window.user_data = user_data;
processdata();
}
}
xmlhttp.open("GET","http://localhost:8888/myphppage.php",true);
xmlhttp.send();
function processdata() {
//split result variable from PHP
var downdata = user_data.split('|||||');
var installedthemes = downdata[0];
currenttheme = downdata[1].toString();
window.currenttheme = currenttheme.toString();
}
function click(e) {
newvar = "001";
//insert css - works with variable newvar but not with this one
chrome.tabs.insertCSS(null,
{file:currenttheme + ".css"});
//alerting the variable works, exactly the same as newvar
alert (currenttheme);
}
document.addEventListener('DOMContentLoaded', function () {
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', click);
}
});
window.user_data = user_data;// <- not required. user_data = xmlhttp.responseText implies user_data is global to this window.
window.currenttheme = currenttheme.toString(); <<- not required too
also downdata[1] IS a string so replace
currenttheme = downdata[1].toString();
with
currenttheme = downdata[1];
If this doesn't help, try alert(currenttheme); and see if you are getting the required theme name, because sometimes PHP can throw errors and die which may not produce a "|||||". Check the php output and alert the xmlhttp.responseText too to see if everything is OK.