I have this following js code to send an audio file to servlet. I need to send two more additional parameters to the servlet. Following is my current code
form = new FormData(),
request = new XMLHttpRequest();
form.append("file",blob, filename);
request.open(
"POST",
"AudioToText",
true
);
request.send(form);
CAn anyone help me with js code how to add additional two parameters like id/pass in this request and how to fetch them in the servlet. Thanks in advance.
The second param in request.open() suppose to point to the file that will process the data in absolute an absolute link, there's also another property of the XMLHttpRequest type called onreadystatechanged which expects a callback that will check to see whether or not the request was successful
Example Code - ignore the lines with self, this those are just variables pointing to methods/properties and are not dependent to perform a request:
// if an Object to connect to server was created begin transfer
if (this.xhr) {
var processData = function () {
// if everything is ok carry on
if (self.xhr.readyState === 4 && self.xhr.status === 200) {
if(self.responseType === "text"){
self.Success(self.xhr.responseText);
}else{
self.Success(self.xhr.responseXML);
}
}
// if something fails along the way else execute failure method
else if (self.xhr.status !== 200 && self.xhr.readyState === 4) {
// something went wrong
}
};
// open connection
this.xhr.open(this.method, this.host, true);
// set up the connection to a method to process the data
//noinspection JSPrimitiveTypeWrapperUsage
this.xhr.onreadystatechange = processData;
// send the data
this.xhr.send(this.postData);
Related
I have a site that makes an HTTP request for JSON data, then a callback function processes the data and displays it by creating a series of divs dynamically. What I want to do is to wait for that function to finish adding the divs to the page, then apply labels only to specific divs created by the previous code.
HTTP Request and Callback
function data(callback){
var url = //request url;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
document.body.className = 'ok';
//Parse returned string into an object, then pass the object to the callback function.
var data = JSON.parse(request.responseText);
callback(data);
} else {
document.body.className = 'error';
}
}
};
request.open("GET", url , true);
request.send(null);
}
function dataDisplay(data){
//outputs <div id="1064" class="displayed-data">
<p id="message1" class="hidden"></p>
}
data(dataDisplay);
The code above displays my data exactly how I want it to, but when I try to access the numbered ID of the divs I want to change, the function runs before the data is displayed on the page, causing a 'null' error because the data I am trying to change hasn't been added to the DOM yet.
Second Function to change original
function label(){
var message1 = document.createTextNode('//some label');
var displayedData = document.getElementById('1064').getElementById('message1');
displayedData.appendChild(message1);
document.getElementById('message1').classList.remove('hidden');
}
How do I get the second function to wait until the callback has completed before trying to access and change it? I tried a callback inside of a callback, something like: label(data(dataDisplay)); but it still threw the same errors, so I clearly did it wrong. Sorry, I am brand new to JavaScript and don't really know where to go from here.
Thanks for your help!
A pretty quick way of doing it correctly is with this inline function.
data(function(result) {
dataDisplay(result);
label();
});
Be aware that your data function itself completes very quickly - if you need something from its result, you will need to include it in its callback.
I am trying to solve this problem of mine: I am making two ajax calls on window.load, and it seems like second AJAX response rewrite first one before I function can proceed it or I am making something wrong... anyway I am not able to solve it without making calls synchronous and i don't really want to do that for obvious reasons.
So Here is my code (Javascript) To Create new XMLHttpRequest:
function createRequest(){
if(window.XMLHttpRequest)
return new XMLHttpRequest;
else
return new ActiveXObject("Microsoft.XMLHTTP");
}
My send request function (to sending them)
function sendRequest( url, callback){
request = createRequest();
if(typeof callback === 'function'){
request.onreadystatechange = callback();
}
request.open("GET", url, true);
request.send();
}
and finally my callback
function handleData(){
return function(){
if (request.readyState == 4 && request.status == 200) {
serverResponse = JSON.parse(request.responseText);
switch(Object.keys(serverResponse)[0]){
case "a": function1(serverResponse.a,"a"); break;
case "b": function2(serverResponse.b,"b"); break;
}
}
}
I am creating my calls like this:
window.onload = function () {
sendRequest('url' , handleData);
sendRequest('url2', handleData);
}
NOTICE: As you can see, this is simplified version of my code.
In a switch I am calling function1 and 2 these functions are really handling JSON response from server. I am making calls on two different urls on a same domain with different json response.
Also when I make only one call it works well(Both of them)... Problem only occurs when I am trying to make 2 in a row - And when i make two calls only second one is processed right. Thats why i am thinking that second overwrite first.
I tried to make two functions to handleData so there was handleData1() and handleData2() instead of single handleData() with switch so i call them like this:
window.onload = function () {
sendRequest('url' , handleData1);
sendRequest('url2', handleData2);
}
but i run into problem where second ajax response(always the second call) but again only second one succeed. And then i put console.log(request) in both of em, and i get only JSON for second function trying to be processed with second function.(nothing about first one) Sometimes is second function called more times like 4.
Btw handleData2 does not depend on data from handleData1.
If any more questions please do ask :) Thanks
request = createRequest();
creates a global variable. Every call to the function will override that variable, which is what you are experiencing.
Create a local variable and pass the value to the callback:
var request = createRequest();
if(typeof callback === 'function'){
request.onreadystatechange = callback(request);
}
// ...
function handleData(request) {
// ...
}
I am able to connect to the webservice. That service has a number of operations that can be executed and return a result. One is called helloWorld. I would like to perform that operation. Right now I specify the web service file, but i need to further specify the method in the file to be executed. Here is what I have:
function soapReq() {
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
// Get the data from the server's response
console.log(ajaxRequest.responseText);
}
}
ajaxRequest.open('POST', 'http://theWebServiceNameThatICannotGiveOut', true);
ajaxRequest.send(null);
}
Can I add the operation to be performed onto the end of the url or something?
You should find something on the server, or find the page that has the hello world operation. Then you can make a request to that page (see example below), and you don't need it to be a POST request, just use GET.
Example:
// something like this:
ajaxRequest.open('GET', 'http://site.xxx/helloWorld.php', true);
// or this
ajaxRequest.open('GET', 'http://site.xxx/helloWorld.php?somevar=somevalue', true);
// or also this
ajaxRequest.open('GET', 'http://site.xxx/somepage.php?op=helloWorld', true);
But I can't help you more than this if you can't provide the site you're trying to make the request to. You should ask someone that works on it or search on the site itself.
I am using the easybitcoin.php script here:
(It makes json-rpc calls to bitcoind)
I've made a seperate php file, that retrieves the data from the easybitcoin.php file such as balance, accounts..etc. And spits it out on a page.
When making a json-RPC call, such as:
retrieve_once('easybitcoin.php');
print_r($<username>->getbalance($_SESSION['username']) );
You need to refresh the page to get your updated balance, how would you make it dynamic where the user does not have to refresh the page.
Thanks for any help.
Make an AJAX GET request:
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "yourPhpFile.php");
client.send();
Create the handler:
function processData(data) {
// taking care of data
}
function handler() {
if(this.readyState == this.DONE) {
if(this.status == 200 &&
this.responseXML != null) {
// success!
processData(this.responseXML);
return;
}
// something went wrong
processData(null);
}
}
In the processData function do whatever you want with the data you receive from the server.
In the yourPhpFile.php you should include the easybitcoin.php file and make the necessary calls.
Now you can encapsulate your AJAX request in setInterval(), this way it will periodically get updates.
I'm creating a very basic dashcode widget. I'm using customized snippets from Apple: xmlRequest setup and xmlLoaded. Below is my code
function sendURL(){
// Values you provide
var textField = document.getElementById("searchqeue"); // replace with ID of text field
var textFieldValue = textField.value;
var feedURL = "feed://isohunt.com/js/rss/"+textFieldValue+"?iht=&noSL"; // The feed to fetch
// XMLHttpRequest setup code
httpFeedRequest = new XMLHttpRequest();
function loadedXML()
{
alert("xmlLoaded");
if (httpFeedRequest.status == 200)
{
// Parse and interpret results
// XML results found in xmlRequest.responseXML
returnvalue = httpFeedRequest.responseText;
alert(returnvalue);
var textField = document.getElementById("resultarea");
textField.value = returnvalue;
// Text results found in xmlRequest.responseText
}
else
{
alert("Error fetching data: HTTP status " + httpFeedRequest.status);
}
}
httpFeedRequest.onload = loadedXML();
alert ("onload executed");
//httpFeedRequest.overrideMimeType("text/html");
httpFeedRequest.open("GET", feedURL);
httpFeedRequest.setRequestHeader("Cache-Control", "no-cache");
// Send the request asynchronously
httpFeedRequest.send(null);
alert("sent");
}
I want to keep it all in one single function to keep it simple. I could ofcourse separate the xmlLoaded function and the sendURL function but for me this is clearer.
the code I get back in the error console:
xmlLoaded (inside the loadedXML function first line)
Error fetching data: HTTP status 0 (the error message from the loadedXML function)
onload executed (the line beneath httpFeedRequest.onload = loadedXML();)
sent (the last line of the function)
Thes esnippets come with dashcode itself, so I guess the problem is with my url. This is a feed:// page instead of a html or xml page. But as feeds are xml too, I though I could just use the xmlRequest. Also, calling the same page with http:// instead of feed:// returns the same.
httpFeedRequest.responseText returns "" (empty string)
httpFeedRequest.responseXML returns null
any help will be more than appreciated!
you have probably sorted this by now but a couple of things.
httpFeedRequest.status == 200 is for http response. if you are calling a feed then it may not give the same numeric response. If you use Safari and go into developer mode and then set a breakpoint on your script and walsk through it you can see the responses that come back to check this.
Also you are not checking the ready state of the request - if(myRequest.readyState == 4)
the readystates are
Number; 0 means uninitialized, open( ) has not yet been called;
1 means loading, send( ) has not been called;
2 means loaded, send( ) has been called, and headers/status are available;
3 means interactive, responseText holds partial data;
4 means completed.
so it is usual to check for 4.
And in httpFeedRequest.open("GET", feedURL); you might try adding the true parameter to tell the request it is asynchronous httpFeedRequest.open("GET", feedURL, true);