I have the code saving an ArrayBuffer (from an XMLHttpRequest call to get an mp3 as an arraybuffer) to a web sql database, retrieving it from a sql query which returns an object ArrayBuffer. However, when I try to decodeAudioData or createBuffer I get a type error.
var buffer = audioContext.createBuffer(result.xtalk,false);
gives an Uncaught TypeError: Type error
if I put an alert in result.xtalk is object ArrayBuffer
This is in Chrome 21.0.1180.75 on a mac
I tried creating an ArrayBuffer and filling it byte by byte then passing that - but that didn't work either.
Check this tutorial.May this would help
var dogBarkingBuffer = null;
var context = new webkitAudioContext();
function loadDogSound(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
context.decodeAudioData(request.response, function(buffer) {
dogBarkingBuffer = buffer;
}, onError);
}
request.send();
}
Refer the following link:-
http://www.html5rocks.com/en/tutorials/webaudio/intro/
Also do "typeof" on the arraybuffer object you are receiving.Arraybuffer have a properties called byteLength.
If its undefined that means the object you received from the sql database is not arraybuffer object
Reference:-https://developer.mozilla.org/en-US/docs/JavaScript_typed_arrays/ArrayBuffer
Related
I have been trying to send this request through the 2captcha API, but the issue is everytime I send it VIA code it gives me the error:
[ERR_INVALID_ARG_TYPE]: The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type object
Any help would be greatly apricated, I keep trying diffrent things but can't seem to get this request to send.
var FormData = require('form-data');
var fs = require('fs');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const data = new FormData();
data.append("key", "96000001977a12e50ca4eb45f104fe1");
data.append("file", "file");
data.append("submit", "00000W0UAAAAAA-ouoKHOnWuQDNymSwDFYeGP300");
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://2captcha.com/in.php?key=962800000a12e50ca4eb45f104fe1&method=userrecaptcha&googlekey=000000UAAAAAA-ouoKHOnWuQDNymSwDFYeG00000&pageurl=https://www.google.com/recaptcha/api2/demo");
xhr.send(data); //problem area
It looks like the particular XMLHttpRequest library you're using does not support the FormData object. See this bug report. In general, it looks like this library hasn't been updated in a while. If it's not too difficult (I don't know how deeply rooted this old library is within your project) but I would recommend switching to a more modern solution, like node-fetch, which uses the newer, easier to use fetch API. This node-fetch package would provide that support for node.
One solution to fix your current problem is to use URLSearchParams which will let you encode data in the same format that you need, shares a similar API to FormData, but also has a toString function. Your error message says that this library supports strings, so you can just pass in a stringified value.
const data = new URLSearchParams();
data.append("key", "xxx");
data.append("file", "file");
data.append("submit", "yyy");
console.log(data.toString())
i'm trying to access a local JSON File with JS, turn it into an JS Object by parsing it and logging it to the console. I'm using Live Server in VS Code to set up the Server, therefore the localhost URL.
var requestURL = "http://localhost:5500/sqVol.json";
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
var jsonObj = request.response;
request.onload = function () {
JSON.parse(jsonObj);
logData(jsonObj);
};
function logData(jsonObj){
console.log("jsonObj= " + jsonObj);
//console.log("jsonObj[Datum]= " + jsonObj[Datum]);
//console.log("jsonObj.Datum= " + jsonObj.Datum);
}
Output: jsonObj= null
The JSON File:
{
"Datum": ["03.05.2017","05.06.2017"],
"Volume": [1338,1445]
}
Here's what I imagine happens:
I'm getting the Answer from localhost and parsing it via JSON.parse into an JS Object. As soon as the request finished im calling my logData function and passing the parsed Data to log it.
As #connexo pointed out I didn't understand the asynchronous nature of the call. And frankly i still don't but i guess a good starting points will be:
How do I return the response from an asynchronous call?
MDN Synchronous and Asynchronous Requests
As #Mani Kumar Reddy Kancharla pointed out my response is already a JS Object since i declared request.responseType = 'json';
This is how it looks right now:
var requestURL = "http://localhost:5500/sqVol.json";
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function () {
console.log(request.response);
var jsonObj = request.response;
logData(jsonObj);
};
function logData(jsonObj){
console.log("jsonObj= " + jsonObj);
console.log("jsonObj[Datum]= " + jsonObj.Datum);
Ouput: {…}
Datum: Array [ "03.05.2017", "05.06.2017" ]
Volume: Array [ 1338, 1445 ]
jsonObj= [object Object]
jsonObj[Datum]= 03.05.2017,05.06.2017
As you can see i can also access the .Datum Property. I Consider it solved. Thank you!
edit: Added the link provided by connexo.
I used the browser XMLHttpRequest object for Ajax about 12 years ago.
https://api.jquery.com/jquery.getjson/
You have two issues in your code:
You're using JSON.parse() too many times on same date which is already converted from JSON string to a JavaScript object and tries to parse a Javascript object raising a Syntax error. You've already mention request.responseType = 'json' i.e. responseType specifies you're receiving a JSON string as response so JavaScript Engine will already parse it and provide you a JavaScript object as request.response and you need not parse it. So you could use JSON.parse(request.responseText) if you want to parse it yourselves or directly use request.response as a JavaScript object.
You're trying to store request.response into a variable outside the load function which will just provide the value of request.response at that time which could be null if the response is not received yet. You need to get the response in the onload fucntion implementation as it is executed once you receive the response.
So what you're looking for overall is this ->
var requestURL = "http://localhost:5500/sqVol.json";
var request = new XMLHttpRequest();
var jsonObj;
function logData(jsonObj){
console.log("jsonObj= " + JSON.stringify(jsonObj));
console.log("jsonObj[Datum]= " + JSON.stringify(jsonObj["Datum"]));
console.log("jsonObj.Datum= " + JSON.stringify(jsonObj.Datum));
// or simply
console.log(jsonObj);
console.log(jsonObj['Datum']);
console.log(jsonObj.Datum);
}
request.onload = function () {
jsonObj = request.response;
logData(jsonObj);
};
request.responseType = 'json';
// finally send the request
request.open('GET', requestURL);
request.send();
Here JSON.stringify() converts a JavaScript Object back to a JSON string.
Refer to this link to get more information on how to use XMLHttpRequest
EDIT: Referring to another answer posted, people simply use libraries like jQuery AJAX to make asynchronous requests to get data from the web, especially in XML or JSON format.
I need to use JQuery ajax to post a complex and sensitive data object (nested objects, arrays, and Personally Identifiable Information) to my server, where a PDF is generated and returned to the client. The client browser then should open the PDF in a new window.
Because of the nature of the data the request neither can nor should be an encoded URL - it must include the data as a JSON body.
The other questions/answers on this subject did not solve the problem in my case or do not do so completely.
Solution
POST with the data in the body as JSON.
Set the expected Content-Type of the response to arraybuffer (on the client and server).
When the request has complete successfully, convert the response to a Blob.
Create an object url to the Blob and open it in a new window.
Notes
JQuery ajax does not support the arraybuffer Content-Type so the base JavaScript xhr must be used (if you don't have any other options).
Internet Explorer has its own functionality for handling and displaying Blob's, so a special case is needed.
Supported browsers does not include IE9
Code
RequestPdf = function (url, data) {
var request = new XMLHttpRequest(), file, fileURL;
request.open("POST", url);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.responseType = "arraybuffer";
request.send(data);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
file = new Blob([request.response], { type: 'application/pdf' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE
window.navigator.msSaveOrOpenBlob(file);
} else {
fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
}
};
};
My goal is to read an HTTP MP3 audio stream from the browser and have access to the raw audio data.
HTML5 < audio > lets me easily play the stream, but, as far as I know, does not grant access to the raw audio data. It just plays it.
JS XMLHTTPRequest can download files through HTTP and process the raw audio data. It seems to be a good candidate, but it suffers from a limitation: it does not grant access to the binary data until the download is finished (readystate = 4). In my case, the stream is unlimited, so the readystate stays permanently at 3 and the XHR response is null (this behavior is detailed in the mozilla documentation). Note that the cross-origin policy of the server I am connecting to is Access-Control-Allow-Origin: *
Code sample that works for local regular files, but not for streams. I get a null pointer exception at request.response.length
request = new XMLHttpRequest();
//request.open('GET', 'test.mp3', true);
request.open('GET', 'http://domain.com/stream.mp3', true);
request.responseType = 'arraybuffer';
request.onload = function() {
console.log("request onload");
var audioData = request.response;
audioCtx.decodeAudioData(audioData,
function(buffer) { myBuffer = buffer; source.buffer = myBuffer; },
function(e){"Error with decoding audio data" + e.err}
);
}
request.onreadystatechange = function() {
console.log("ready state = " + request.readyState);
console.log(request.response.length);
}
request.send();
Does anybody know alternatives or workarounds to those options, so that the raw binary packets can be read while downloading the stream?
Note that I don't have control on the server. It's an icecast http stream.
Also, on the browser side, I'd like to avoid using Flash.
Thank you
Edit: to clarify possible cross-origin questions, the JS is run on a page hosted in a localhost server.
The following workaround worked:
As stated in MDN https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data, it is possible to override the MIME type of http request, setting it to custom, and call responseText.
function load_binary_resource(url) {
var req = new XMLHttpRequest();
req.open('GET', url, false);
//XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
req.overrideMimeType('text\/plain; charset=x-user-defined');
req.send(null);
if (req.status != 200) return '';
return req.responseText;
}
The point is that req.responseText does not suffer from the same limitation of req.response. It is not null in the state readystate=3.
Then, the binary responseText is accessed with
var filestream = load_binary_resource(url);
var abyte = filestream.charCodeAt(x) & 0xff; // throw away high-order byte (f7)
A significant drawback is that req.responseText keeps growing as the stream is downloaded. The request should be reset from time to time to avoid excessive RAM consumption.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting BLOB data from XHR request
I try to get an image from my server dynamically, but the XMLHTTPRequest returns null in the response. The Google Chrome network tool tells me that he loaded the day1.jpg, but the blob variable is null...
var xhr = new XMLHttpRequest(), blob;
xhr.open("GET", "day1.jpg", true);
// Set the responseType to blob
xhr.responseType = "blob";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
console.log("Image retrieved");
blob = xhr.response;
console.log("blob: " + blob);
}
}, false);
// Send XHR
xhr.send();
The output is:
Image retrieved
blob: null
The reason is a bug on the Chrome side (also available on v18). Reported here
why use ajax to load the image (as far as I know you can't http://www.mail-archive.com/discuss#jquery.com/msg00377.html)? You can just dynamically generate an image element and set the src attribute to the image on your server.
var i = new Image();
i.onload = function()
{
//do the stuff you need to do once it loads here
}
i.src = "day1.jpg";
Use the console to inspect the xhr object and see if it's being populated at all
I doubt that you can load images from the server dynamically, instead what you can do is update the image source dynamically and tell from whci location shoul the image be fetched/loaded