How do I send data to JavaScript methods/functions?
I saw toast examples with javascriptInterface, but I am unable to relate it to my scenario.
My JavaScript function:
function printInfo() {
var request = new AudioFileRequest('1.wav');
request.send();
}
I want to record the sound in mobile and send that sound file to the method "AudioFileRequest".
I assume that you already loaded a file with the printInfo function to a web view.
To execute some JavaScript code from the Java side you may load a JavaScript function, for example:
String data = "1.wav";
webview.loadUrl("javascript:printInfo('" + data + "')");
And your JavaScript function is:
function printInfo(fileName) {
var request = new AudioFileRequest(fileName);
request.send();
}
Related
I'm trying to save a post request data to a google spreadsheet. However, the data is saved as undefined.
The original post uses a form and uses jquery. See the link below. But I'm trying to pass an array also without the use of jquery.
I'm using the following app script without using jquery - https://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/
I'm posting the code here.
function sendData(data) {
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "spreadsheeturl";
xmlhttp.open("post", theUrl);
//xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send(JSON.stringify(data))
}
I found the answer, you have to uncomment a block in the app script if you are passing JSON data.
I am trying to make a function call in a post-request with AJAX to a function I have defined in the #function{}-tag to do a refresh of the page. I am trying to make a file upload function. This is my Razor function:
public string UploadFile(string filePath, string fileContent)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("uploads");
container.CreateIfNotExists();
container.SetPermissions(
new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
CloudBlockBlob blockBlob = container.GetBlockBlobReference(filePath);
using (var fileStream = new System.IO.MemoryStream(Convert.FromBase64String(fileContent)))
{
blockBlob.UploadFromStream(fileStream);
}
string test = storageAccount.ToString();
return filePath + " " + test + " " + fileContent;
}
How exactly do I make a function call when it is in the same document because of the way C1 CMS works?
I know I cannot make a simple function call since the server code is already rendered before the javascript is loaded. This is what i have so far in terms of my post request:
function postUpload(){
$.ajax({
url: '#UploadFile("testFilePath","testData")',
data: "",
type: 'POST',
cache: false,
});
}
To solve this I changed my entire function in C1 CMS to a User Control Function instead. Then I separated the HTML and the code into two different files. Furthermore I converted most of the code to client-side, and set a value in a hiddenfield on postback in order to send the desired information to the server.
Why don't you just define the UploadFile function in your controller as an AJAX action?
There doesn't seem to be anything in your function that would require the server to know about what's happening on the client side.
So I know this is so lame to ask this question as I have spent a day searching on this subject without any success. As many others, I'm facing the crossdomain problem. The suggestion I see everywhere is to update the JSON file on a server or use localhost which I can't use because my assignment is not allowed to do so.
I am posting this question hoping there is some other solution for this.
I need to fetch data from a JSON file locally using pure JavasSript and Ajax which does not involve hosting on a server nor localhost (using absolute path is also a bad idea).
This is my code so far:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', '/json/userinfo.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
(function() {
loadJSON(function(response){
var actual_JSON = JSON.parse(response);
console.log(actual_JSON);
})
})()
You won't be able to access local files using AJAX/XHR. Its not designed for this purpose.
What you can do is assign your json data into a variable in the json file,
var data = [{
}];
and then load your json file using script tag like below:
<script type="text/javascript" src="file_name.json"></script>
Now all the json data can be accessed using the data variable.
I'm making a JavaScript script that is going to essentially save an old game development sandbox website before the owners scrap it (and lose all of the games). I've created a script that downloads each game via AJAX, and would like to somehow upload it straight away, also using AJAX. How do I upload the downloaded file (that's stored in responseText, presumably) to a PHP page on another domain (that has cross origin headers enabled)?
I assume there must be a way of uploading the data from the first AJAX request, without transferring the responseText to another AJAX request (used to upload the file)? I've tried transferring the data, but as expected, it causes huge lag (and can crash the browser), as the files can be quite large.
Is there a way that an AJAX request can somehow upload individual packets as soon as they're recieved?
Thanks,
Dan.
You could use Firefox' moz-chunked-text and moz-chunked-arraybuffer response types. On the JavaScript side you can do something like this:
function downloadUpload() {
var downloadUrl = "server.com/largeFile.ext";
var uploadUrl = "receiver.net/upload.php";
var dataOffset = 0;
xhrDownload = new XMLHttpRequest();
xhrDownload.open("GET", downloadUrl, true);
xhrDownload.responseType = "moz-chunked-text"; // <- only works in Firefox
xhrDownload.onprogress = uploadData;
xhrDownload.send();
function uploadData() {
var data = {
file: downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1),
offset: dataOffset,
chunk: xhrDownload.responseText
};
xhrUpload = new XMLHttpRequest();
xhrUpload.open("POST", uploadUrl, true);
xhrUpload.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhrUpload.send(JSON.stringify(data));
dataOffset += xhrDownload.responseText.length;
};
}
On the PHP side you need something like this:
$in = fopen("php://input", "r");
$postContent = stream_get_contents($in);
fclose($in);
$o = json_decode($postContent);
file_put_contents($o->file . '-' . $o->offset . '.txt', $o->chunk);
These snippets will just give you the basic idea, you'll need to optimize the code yourself.
I am building a javascript component for Firefox that will take in a zip code, and will return the current weather conditions.
The sample code that weather underground uses jQuery, but as I understand it, I cannot include this code in my javascript component, as javascript does not have the functionality to include other javascript files.
At any rate, I have built up my skeleton code. It takes in the zip code and builds up the url
(example: http://api.wunderground.com/api/e17115d7e24a448e/geolookup/conditions/q/22203.json)
I have tried downloading the data from that url, via the following method:
getWeatherByUrl: function(url)
{
var persist = Components.classes["#mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);
var file = Components.classes["#mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD",Components.interfaces.nsILocalFile);
file.append("weather-forecaster.dat");
var urlURI = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(url, null, null);
persist.saveURI(urlURI,null,null,null,"",file);
return url;
}
This should download the file to the user's profile directory. It indeed does create the file there. However, it does not look like it contains the json data from weather underground.
What exactly is going on? How would I download the file? I believe that there is a query going on when that url is passed to weather underground, but that shouldn't matter as the .json page is what gets spit out from them, right?
Is there a way to do this without downloading the file, but by streaming it and parsing it?
You can simply use XMLHttpRequest to download this data:
var request = Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
request.open("GET", "http://api.wunderground.com/api/Your_Key/geolookup/conditions/q/IA/Cedar_Rapids.json");
request.addEventListener("load", function(event)
{
var data = JSON.parse(request.responseText);
alert(data.response.version);
}, false);
request.send(null);