javascript drive api gapi client request with variable - javascript

I need to search for a folder in Google Drive, through a html page with javascript.
I have a javascript function that works:
function listFiles() {
var request = gapi.client.drive.files.list({
q: " mimeType = 'application/vnd.google-apps.folder' and name='SearchFolder' ",
pageSize: 10,
fields: "nextPageToken, files(id, name)"
});
request.execute(function (resp) {
console.log('Files:');
var files = resp.files;
if (files && files.length > 0) {
var file = files[0];
console.log(file.name + ' (' + file.id + ')');
} else {
console.log('No files found.');
}
});
Instead of that string at the q parameter, i tried to use something like this:
var folderSearch= 'TypeNameHere';
var string =JSON.stringify('mimeType = '+"'"+'application/vnd.google-apps.folder'+ "'"+' and name='+"'"+folderSearch+ "'" );
var request = gapi.client.drive.files.list({
q: string,
pageSize: 10,
fields: "nextPageToken, files(id, name)" });
But it doesn't work. How can I pass a variable in the request?

You had the right idea - just don't use JSON.stringify. That's for serialising (converting) an object to a string, but it's already a string.
Change the string to this...
var string = " mimeType = 'application/vnd.google-apps.folder' and name='" + folderSearch + "' ";

Related

JQuery $.getJSON asynchronous workaround - caching ajax results

I am caching the JSON returned from ajax calls and then displaying the results from the cache. My issue is if there is no cache for that Ajax call already, the results only display on refresh. This is down to the fact that ajax is asynchronous but how do I get around that? Ajax async:false has been deprecated so that's not an option. Would the $.getJSON .done() function suffice or is there a better way?
Here is my code so far:
if ((online === true)) {
//get JSON
$.getJSON(baseurl + '/wp-json/app/v2/files?filter[category]' + cat + '&per_page=100', function(jd) {
//cache JSON
var cache = {
date: new Date(),
data: JSON.stringify(jd)
};
localStorage.setItem('cat-' + cat, JSON.stringify(cache));
});
//if not online and no cached file
} else if ((online === false) && (!cache['cat-' + cat])) {
alert('There are no cached files. You need to be online.');
}
//get cached JSON
cache['cat-' + cat] = JSON.parse(localStorage.getItem('cat-' + cat));
var objCache = cache['cat-' + cat].data;
objCache = JSON.parse(objCache); //Parse string to json
//display JSON results from cache
$.each(objCache, function(i, jd) {
var thumb = jd.file_thumbnail.sizes.medium;
//.....etc...
)
}}
A simple rewrite of your code yields the following:
function cacheAsCacheCan(cat, callback) {
if (online === true) {
//get JSON
$.getJSON(baseurl + '/wp-json/app/v2/files?filter[category]' + cat + '&per_page=100', function(jd) {
//cache JSON
var cache = {
date: new Date(),
data: JSON.stringify(jd)
};
localStorage.setItem('cat--' + cat, JSON.stringify(cache));
});
//if not online and no cached file
} else if ((online === false) && (!cache['cat-' + cat])) {
callback('There are no cached files. You need to be online.');
return;
}
//get cached JSON
callback(null, cache['cat-' + cat] = JSON.parse(localStorage.getItem('cat-' + cat)));
}
cacheAsCacheCan('someCat', function(error, cachedata) {
if(error) {
alert(error);
} else {
var objCache = cachedata.data;
objCache = JSON.parse(objCache); //Parse string to json
//display JSON results from cache
$.each(objCache, function(i, jd) {
var thumb = jd.file_thumbnail.sizes.medium;
//.....etc...
)
}
}
);

How do I download a file that is returned by the server in an Ajax call?

I have a download function where the idea is that when the user clicks a button, it does an ajax call to a function that will create a csv file containing all of the information the user was viewing, and will return the file as a download. I have the server function creating a csv file, but I'm not sure how to make it download. This is my server-side code:
public ActionResult Download(Guid customerOrderId)
{
var order = this.UnitOfWork.GetRepository<CustomerOrder>().Get(customerOrderId);
var csv = new StringBuilder();
csv.Append("Customer,Bill To Name,Ship To Name,Patient,Order#,Order Date," +
"Line,Item#,Item Description,Qty,UOM,Price,Ext Price,Carrier," +
"Notes,Purchase Order");
var customer = order.CustomerNumber;
var billToName = order.BTDisplayName;
var shipToName = order.ShipTo.CustomerName;
var orderNum = order.OrderNumber;
var orderDate = order.OrderDate;
var carrier = order.ShippingDisplay;
var notes = order.Notes;
var subtotal = order.OrderSubTotalDisplay;
var total = order.OrderGrandTotalDisplay;
var shipping = order.ShippingAndHandling;
var tax = order.TotalSalesTaxDisplay;
var patient = "";
var purchaseOrder = order.CustomerPO;
foreach (var cartLine in order.OrderLines)
{
var line = cartLine.Line;
var itemNum = cartLine.Product.ProductCode;
var itemDesc = cartLine.Description;
var qty = cartLine.QtyOrdered;
var uom = cartLine.UnitOfMeasure;
var price = cartLine.ActualPriceDisplay;
var ext = cartLine.ExtendedActualPriceDisplay;
//Customer,Bill To Name,Ship To Name,Patient,Order#,Order Date," +
//"Line,Item#,Item Description,Qty,UOM,Price,Ext Price,Carrier," +
//"Notes,Purchase Order
var newLine = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}",
customer, billToName, shipToName, patient, orderNum, orderDate, line, itemNum, itemDesc,
qty, uom, price, ext, carrier, notes, purchaseOrder);
csv.AppendLine(newLine);
}
csv.AppendLine();
csv.AppendLine("Subtotal,Shipping & Handling,Tax,Total");
csv.AppendLine(string.Format("{0},{1},{2},{3}", subtotal, shipping, tax, total));
var filename = "MSD-Order-" + orderNum + ".csv";
var bytes = Encoding.UTF8.GetBytes(csv.ToString());
return this.File(bytes, "text/csv");
}
And here is the ajax method:
function download(customerOrderId) {
$.ajax({
url: insite.core.actionPrefix + '/Checkout/Download/?customerOrderId=' + customerOrderId,
type: 'Post',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
success: function (data) {
alert("downloaded");
},
error: function (ex) {
console.log(ex);
}
});
}
In the success of the ajax call, I checked the value of "data" and it has the information, but I'm not sure how to make it download. What do I do once I receive the data?
Can't you just download it via a href like this?
public FileContentResult Download(Guid customerOrderId)
{
// your code
var response = new FileContentResult(bytes, "text/csv");
response.FileDownloadName = filename;
return response;
}
The link:
Download
You can store the file on server and send the URL with response. Then on ajax success function window.location=data.URL
Venerik has a valid answer as well, but keeping in line with your current implementation, I'd suggest the following.
You can return the string of the URL after saving the file to your server. Then do the window location redirection upon your success. I removed the variable assignments since nothing is being done with them other than sending to a method.
Here we write the file and return the string. You'll need to adjust the return to match your site information, etc.
public ActionResult Download(Guid customerOrderId)
{
var order = this.UnitOfWork.GetRepository<CustomerOrder>().Get(customerOrderId);
var csv = new StringBuilder();
csv.AppendLine("Customer,Bill To Name,Ship To Name,Patient,Order#,Order Date," +
"Line,Item#,Item Description,Qty,UOM,Price,Ext Price,Carrier," +
"Notes,Purchase Order");
foreach (var cartLine in order.OrderLines)
{
//Customer,Bill To Name,Ship To Name,Patient,Order#,Order Date," +
//"Line,Item#,Item Description,Qty,UOM,Price,Ext Price,Carrier," +
//"Notes,Purchase Order
csv.AppendLine(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}",
order.CustomerNumber, order.BTDisplayName, order.ShipTo.CustomerName, "", order.OrderNumber, order.OrderDate, cartLine.Line, cartLine.Product.ProductCode, cartLine.Description,
cartLine.QtyOrdered, cartLine.UnitOfMeasure, cartLine.ActualPriceDisplay, cartLine.ExtendedActualPriceDisplay, order.ShippingDisplay, order.Notes, order.CustomerPO));
}
csv.AppendLine();
csv.AppendLine("Subtotal,Shipping & Handling,Tax,Total");
csv.AppendLine(string.Format("{0},{1},{2},{3}", order.OrderSubTotalDisplay, order.ShippingAndHandling, order.TotalSalesTaxDisplay, order.OrderGrandTotalDisplay));
var filename = "MSD-Order-" + orderNum + ".csv";
using (StreamWriter sw = File.CreateText(Server.MapPath("~/files/" + filename))
{
sw.Write(csv.ToString());
}
// adjust your url accordingly to match the directory to which you saved
// '/files/' corresponds to where you did the File.CreateText
// returning Content in an ActionResult defaults to text
return Content("http://foo.com/files/" + filename);
}
And in your AJAX method update your success function to redirect the page which will prompt the download:
function download(customerOrderId) {
$.ajax({
url: insite.core.actionPrefix + '/Checkout/Download/?customerOrderId=' + customerOrderId,
type: 'Post',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
success: function (data) {
window.location.href = data;
},
error: function (ex) {
console.log(ex);
}
});
}

Creating a CSV file from a Meteor.js Collection

I've written my code so far and can get a list of all the records to show up on a webpage, however I need to be able to get it as a CSV (comma separated values) file.
Right now the page shows a list like follows:
Name Address Description
Bob 1 street Journalist
Bill 2 street Fireman
etc...
Anyway I can have meteor create a CSV file for download, instead of it showing up as a webpage with all the HTML markup?
Based on How to serve a file using iron router or meteor itself?
HTML:
<template name="blah">
Download the CSV
</template>
JS:
// An example collection
var DummyData = new Mongo.Collection("dummyData");
// create some sample data
if (Meteor.isServer) {
Meteor.startup(function() {
var dummyDataCursor = DummyData.find();
if (dummyDataCursor.count() === 0) {
for(var i=1; i<=100; i++) {
DummyData.insert({Name: "Name" + i,Address: "Address" + i, Description:"Description" + i});
}
}
});
}
Router.route('/csv', {
where: 'server',
action: function () {
var filename = 'meteor_dummydata.csv';
var fileData = "";
var headers = {
'Content-type': 'text/csv',
'Content-Disposition': "attachment; filename=" + filename
};
var records = DummyData.find();
// build a CSV string. Oversimplified. You'd have to escape quotes and commas.
records.forEach(function(rec) {
fileData += rec.Name + "," + rec.Address + "," + rec.Description + "\r\n";
});
this.response.writeHead(200, headers);
return this.response.end(fileData);
}
});

Plupload chunk size renaming file to Blob

I'm using Plupload in order to download file. The configuration we have is the folowing :
$("#uploadData").pluploadQueue({
// General settings
runtimes: 'html5,flash,silverlight,html4',
url: serviceurl,
// Maximum file size
max_file_size: '50mb',
chunk_size: '1mb',
max_file_count: 50,
unique_names: true,
// Resize images on clientside if we can
resize: {
width: 200,
height: 200,
quality: 90,
crop: true // crop to exact dimensions
},
// Specify what files to browse for
filters: [
{ title: "Documents Excel", extensions: "xlsx" }
],
init: {
FilesAdded: function (up, files) {
up.start();
},
UploadComplete: function (up, files) {
if (up.total.uploaded == up.files.length) {
$(".plupload_buttons").css("display", "inline");
$(".plupload_upload_status").css("display", "inline");
up.init();
}
}
},
The problem i have is when i upload a file that is bigger than 1MB, i don't receive the right name, instead i receive Blob for name.
For exemple, the name of my file is "Test.xlsx" and the size is 2MB, i will receive, on the server side, "blob" for name and not Test.
Limitation, i'm not allowed to change the chuck size limitation on the client.
How can i get the right name.
Thank for your help.
code used to receive the data on the server side :
[System.Web.Mvc.HttpPost]
public ActionResult UploadData(int? chunk, string name)
{
var fileUpload = Request.Files[0];
if (Session["upDataFiles"] == null)
{
Session["upDataFiles"] = new List<FileUploadViewModel>();
}
Session["upDataFiles"] = UpdateTempDataUpload(fileUpload.FileName, name, (List<FileUploadViewModel>)Session["upDataFiles"]);
UploadFile(chunk, name);
return Content("chunk uploaded", "text/plain");
}
private void UploadFile(int? fileChunk, string fileName)
{
var fileUpload = Request.Files[0];
var uploadPath = Server.MapPath("~/App_Data");
var fullPath = Path.Combine(uploadPath, fileName);
fileChunk = fileChunk ?? 0;
using (var fs = new FileStream(Path.Combine(uploadPath, fileName), fileChunk == 0 ? FileMode.Create : FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
var buffer = new byte[fileUpload.InputStream.Length];
fileUpload.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
fs.Close();
}
}
When i check the name in the request.File object, it's blob and not the actual name.
This issue was described in detail on GitHub. It might be a little confusing, but from what I understand:
$_FILES[ 'name' ] will obligatorily be 'blob' if you use chunks.
They seem to claim that $_REQUEST[ 'name' ] should have the real name, but the users seem to disagree.
As a workaround it is proposed to send the filename along in another form field or url parameter (using for example the BeforeUpload event to set that information). You can set multipart_params and store your information on the file object that you added before or look at a field in your html to get information at this point.
To extend the answer by nus a bit:
I used the BeforeUpload event in Javascript as described in the GitHub post and then had to make a change server-side.
Previously, to get the file name I'd used:
var file = Request.Files[f];
var fileName = file.FileName
However, this had been where 'blob' was being returned. Instead, I made a change so while I still used Request.Files[f] for the file details, I derived the file name like so:
var file = Request.Files[f];
var fileName = Request.Params["name"];
Use BeforeUpload event under init as below:
init : {
BeforeUpload: function(up, file) {
log('[BeforeUpload]', 'File: ', file);
}
}
Also add log function:
function log() {
var str = "";
plupload.each(arguments, function(arg) {
var row = "";
if (typeof(arg) != "string") {
plupload.each(arg, function(value, key) {
// Convert items in File objects to human readable form
if (arg instanceof plupload.File) {
// Convert status to human readable
switch (value) {
case plupload.QUEUED:
value = 'QUEUED';
break;
case plupload.UPLOADING:
value = 'UPLOADING';
break;
case plupload.FAILED:
value = 'FAILED';
break;
case plupload.DONE:
value = 'DONE';
break;
}
}
if (typeof(value) != "function") {
row += (row ? ', ' : '') + key + '=' + value;
}
});
str += row + " ";
} else {
str += arg + " ";
}
});
var log = $('#log');
log.append(str + "\n");
// log.scrollTop(log[0].scrollHeight);
}
And then you can get Filename in $_POST['name'] or $_REQUEST['name'].
Also you can set unique_names as false.
You can also find help here

Get stock quotes from yahoo finance in json format using a javascript

I was trying to get stock quotes from yahoo api.
My input to the query is only a stock ticker ( from a text field). On button click the background JavaScript method "getprice()" is called.
I have a java script code that looks like this
function getprice()
{
var symbol = $('#stockquote').val();
var url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22"+symbol+"%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json";
$.getJSON(url, function (json)
{
var lastquote = json.query.results.quote.LastTradePriceOnly;
$('#stock').text(lastquote);
});
}
$('#stock').text(lastquote);
Here "stock" is the text field where I want to display the LastTradePriceOnly for the given ticker.
I do not see any output turning up.
Debugging also does not show up any errors.
Can I get any suggestions with this issue?
Try this.
function getData() {
var url = 'http://query.yahooapis.com/v1/public/yql';
var symbol = $("#symbol").val();
var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");
$.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
.done(function (data) {
$('#result').text("Price: " + data.query.results.quote.LastTradePriceOnly);
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log('Request failed: ' + err);
});
}
Here I also added working example for you.
This is how it's done in AngularJS in case you need it:
In your view:
<section ng-controller='StockQuote'>
<span>Last Quote: {{lang}}, {{lastTradeDate}}, {{lastTradeTime}}, {{lastTradePriceOnly}}</span>
</section><br>
In your controller: The stock symbol name is passed via $scope.ticker_name to service method 'getData.getStockQuote'.
appModule.controller('StockQuote', ['$scope', 'getData',
function($scope, getData) {
var api = getData.getStockQuote($scope.ticker_name);
var data = api.get({symbol:$scope.ticker_name}, function() {
var quote = data.query.results.quote;
$scope.lang = data.query.lang;
$scope.lastTradeDate = quote.LastTradeDate;
$scope.lastTradeTime = quote.LastTradeTime;
$scope.lastTradePriceOnly = quote.LastTradePriceOnly;
});
}]);
In your service:
appModule.service('getData', ['$http', '$resource', function($http, $resource) {
// This service method is not used in this example.
this.getJSON = function(filename) {
return $http.get(filename);
};
// The complete url is from https://developer.yahoo.com/yql/.
this.getStockQuote = function(ticker) {
var url = 'http://query.yahooapis.com/v1/public/yql';
var data = encodeURIComponent(
"select * from yahoo.finance.quotes where symbol in ('" + ticker + "')");
url += '?q=' + data + '&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
return $resource(url);
}
}]);

Categories