I want to insert, update data from the fusion tables.
While selecting from the fusion table all seems to work fine. But during row addition i need to used OAuth 2.0 but unable to find a suitable solution to get the access token and use it during the insert.
A code sample would help a lot.
var fusiondata;
function initialize() {
// Initialize JSONP request
var script = document.createElement('script');
var url = ['https://www.googleapis.com/fusiontables/v1/query?'];
url.push('sql=');
var query = 'insert into 1bPbx7PVJU9NaxgAGKqN2da4g5EbXDybE_UVvlAE (name,luckynumber) values('abc',89)';
var encodedQuery = encodeURIComponent(query);
url.push(encodedQuery);
url.push('&callback=viewData');
url.push('&key=AIzaSyA0FVy-lEr_MPGk1p_lHSrxGZDcxy6wH4o');
script.src = url.join('');
var body = document.getElementsByTagName('body')[0];
body.appendChild(script);
}
function viewData(data) {
// code not required
}
I know most of you are suffering for google auth and inserting and updating fusion table. I am providing the entire code how to use the gauth lib to insert in a simple manner
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Authorization Request</title>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
function auth() {
var config = {
'client_id': '365219651081-7onk7h52kas6cs5m17t1api72ur5tcrh.apps.googleusercontent.com',
'scope': 'https://www.googleapis.com/auth/fusiontables'
};
gapi.auth.authorize(config, function() {
console.log('login complete');
console.log(gapi.auth.getToken());
});
}
function insert_row(){
alert("insert called");
gapi.client.setApiKey('AIzaSyA0FVy-lEr_MPGk1p_lHSrxGZDcxy6wH4o');
var query = "INSERT INTO 1T_qE-o-EtX24VZASFDn6p3mMoPcWQ_GyErJpPIc(Name, Age) VALUES ('Trial', 100)";
gapi.client.load('fusiontables', 'v1', function(){
gapi.client.fusiontables.query.sql({sql:query}).execute(function(response){console.log(response);});
});
}
</script>
</head>
<body>
<button onclick="auth();">Authorize</button>
<p> </p>
<button onclick="insert_row();">Insert Data</button>
</body>
</html>
Related
The file name is called clik.js here I have to access some values from controller/view
Using view I have tried this code:
<head>
#if (ViewBag.status != null)
{
<script type="text/javascript">
var tagAccess='#ViewBag.status[0]';
</script>
<script src="~/JavaScript/click.js"></script>
}
</head>
Using this code, I could get single value in js file. But I have to get all values
//var tagAccess='#ViewBag.status';
If I write the code like this, I didn't get any output
You can serialize the Item using this:
<script>
var tagAccess = #Html.Raw(Json.Serialize(#ViewBag.status[0]));
</script>
Can somebody help in displaying webapi data in angularjs repeat directive in my first Angular application?
I'm getting data from the WEBAPI as expected like below
[{"FLAVOR_ID":"BES","FLAVOR_NAME":"BES"},{"FLAVOR_ID":"BUN","FLAVOR_NAME":"BUN"}]
API Controller:
public class ItemMaintenanceController : ApiController
{
ItemMaintenanceRepository itemRepository;
public ItemMaintenanceController(ItemMaintenanceRepository _itemRepository)
{
itemRepository = _itemRepository;
}
[HttpGet]
public IEnumerable<MA_Flavor> GetAllFlavors()
{
return itemRepository.GetAllFlavors();
}
}
Client.html:
<!DOCTYPE html>
<html>
<head>
<title> Client</title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-resource.js"></script>
<script>
alert("start");
var app = angular.module("myapp", ['ngResource']);
var controller = function ($scope, $resource) { // controller uses $resource, which is part of ngResource
$scope.flavor = {};
$scope.getFlavors = function () {
alert("calling getflvors");
var request = $resource("http://localhost:55762/api/ItemMaintenance/GetAllFlavors?Id=CMN");
$scope.flavor = request.query();
};
////$scope.clear = function () {
//// $scope.flavor = {};
//// $scope.error = "";
////}
$scope.getFlavors();
myapp.controller("ItemMaintenanceController", controller);
</script>
</head>
<body ng-app="contacts">
<div ng-controller="ItemMaintenanceController">
<select ng-model="flavor">
<option ng-repeat="fl in Flavor" value="{{fl.FLAVOR_NAME}}">{{fl.FLAVOR_NAME}}</option>
</select>
<h1>You selected: {{flavor.FLAVOR_NAME}}</h1>
</div>
</body>
</html>
Looks like issue with the names of the ng-controller, ng-module and ng-app. Try to change and hope it will work.
<body ng-app="contacts">
<div ng-controller="ItemMaintenanceController">
<Script>
var app = angular.module('contacts', []);
// To fetch all falvors
app.controller("ItemMaintenanceController", function ($scope, $http) {
.....
...
</script>
I think you're close. based on what you have I think something like this should work:
<select ng-model="selectedFlavorId">
<option ng-repeat="fl in flavor" value="{{fl.FLAVOR_ID}}">{{fl.FLAVOR_NAME}}</option>
</select>
your data is in $scope.flavor and I assume that if you debug it will look like this:
$scope.flavor = [{"FLAVOR_ID":"BES","FLAVOR_NAME":"BES"},{"FLAVOR_ID":"BUN","FLAVOR_NAME":"BUN"}]
you want the id in your value field as that is the bit you need to know which value you selected. the value you see in dropdown should be the name of the flavor.
when you select something, that value will be reflected in the model.
as I chose selectedFlavorId, you will find that populated under $scope.selectedFlavorId. Do not override your API data with the selected value like you've just done.
selectedFlavorId will give you the ID of the item you selected so you need a bit more code after this to get the name of that property from your data array.
There may following issues in your code.
Your angular modules defined as myapp and in ng-app you have used
contacts.
You have to create two different scope variables, one for the flavor
and another is flavors. flavors you need to use under the ng-options
and flavor you have to use for ng-model.
What I understood request.query() will return the resource object,
So have two options to get data from the query. More details about
the resource you can find here
var request = $resource("http://localhost:55762/api/ItemMaintenance/GetAllFlavors?Id=CMN");
Option 1
request.query(function(data) {
$scope.flavor = data;
});
Option 2
request.query().$promise.then(function(data) {
// success
$scope.flavor = data;
}, function(errResponse) {
// fail
});
Supposedly, when a file included in a bundle is modified, the url key is supposed to be updated, forcing the client to clear its cache.
However, I have found this to be a very unreliable process - for some reason, the URL key is not always changed even when there are many changes to the underlying files.
So what I wanted to do was to use the assembly version in the query string so that whenever a release occurred, all clients would clear their cache so that they would be updated to the most recent version. Here is what I have so far:
Custom transform to modify query variables:
public class VersionBusterTransform : IBundleTransform
{
public void Process(BundleContext context, BundleResponse Response)
{
string query = string.Format("{0}.{1}.{2}.{3}", Global.Properties.Version.Major, Global.Properties.Version.Minor, Global.Properties.Version.Release, Global.Properties.Version.Build);
Array.ForEach(Response.Files.ToArray(), x => x.IncludedVirtualPath = string.Concat(x.IncludedVirtualPath, "?v=", query));
}
}
Registering the files:
BundleTable.EnableOptimizations = (Global.Properties.Deployment.Environment != DeploymentEnvironment.Development);
var StyleLibrary = new StyleBundle(ConfigBundles.Styles);
StyleLibrary.Include("~/Content/Styles/Libraries/core-{version}.css", new CssRewriteUrlTransform());
StyleLibrary.Include("~/Content/Styles/Libraries/icomoon/style.css", new CssRewriteUrlTransform());
StyleLibrary.Include("~/Content/Styles/Site.css", new CssRewriteUrlTransform());
StyleLibrary.Transforms.Add(new VersionBusterTransform());
BundleTable.Bundles.Add(StyleLibrary);
var ScriptLibrary = new ScriptBundle(ConfigBundles.Scripts);
ScriptLibrary.Include("~/Content/Scripts/Libraries/modernizr-{version}.js");
ScriptLibrary.Include("~/Content/Scripts/Libraries/bootstrap-{version}.js");
ScriptLibrary.Include("~/Content/Scripts/Framework/yeack.js");
ScriptLibrary.Transforms.Add(new JsMinify());
ScriptLibrary.Transforms.Add(new VersionBusterTransform());
BundleTable.Bundles.Add(ScriptLibrary);
Method to get URL:
public static string Query(string Path)
{
if (HttpRuntime.Cache[Path] == null)
{
var absolutePath = HostingEnvironment.MapPath(Path);
HttpRuntime.Cache.Insert(Path, string.Format("{0}?v={1}.{2}.{3}.{4}", Path, Global.Properties.Version.Major, Global.Properties.Version.Minor, Global.Properties.Version.Release, Global.Properties.Version.Build), new CacheDependency(absolutePath));
}
return HttpRuntime.Cache[Path] as string;
}
Header template:
#Styles.Render(ConfigBundles.Styles)
#Scripts.Render(ConfigBundles.Scripts)
Currently, when I open the site in the Development environment, the following references are printed in the header:
<link href="/Content/Styles/Libraries/core-3.1.0.css?v=0.3.5.0" rel="stylesheet">
<link href="/Content/Styles/Libraries/icomoon/style.css?v=0.3.5.0" rel="stylesheet">
<link href="/Content/Styles/Site.css?v=0.3.5.0" rel="stylesheet">
<script src="/Content/Scripts/Libraries/modernizr-2.6.2.js?v=0.3.5.0"></script>
<script src="/Content/Scripts/Libraries/bootstrap-3.0.0.js?v=0.3.5.0"></script>
<script src="/Content/Scripts/Framework/yeack.js?v=0.3.5.0"></script>
However, in Production, it is printing this:
<link href="/Content/Styles/css?v=SmKL_qNLRzByCaBc0zE--HPqJmwlxxsS9p8GL7jtFsc1" rel="stylesheet">
<script src="/Content/Scripts/js?v=YvUa47U8N_htaVmoq5u1VzHyRgEH3quFSUYpjRonpbM1"></script>
Why doesn't my bundling transform have any effect on what is printed in production?
I have the following code to authenticate a user via the Google+ signin button:
<html>
<head>
<!-- google api -->
<meta name="google-signin-client_id" content="xxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com">
<meta name="google-signin-scope" content="email">
</head>
<body>
<div id="google-signin"></div>
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
function onGoogleSuccess(googleUser) {
// get the token
var id_token = googleUser.getAuthResponse().id_token;
// console.log('Logged in as: ' + googleUser.getBasicProfile().getName());
}
function onGoogleFailure(error) {
console.log(error);
}
function renderButton() {
gapi.signin2.render('google-signin', {
'scope': 'https://www.googleapis.com/auth/plus.login',
'width': 242,
'height': 56,
'longtitle': true,
'theme': 'dark',
'onsuccess': onGoogleSuccess,
'onfailure': onGoogleFailure
});
}
</script>
</body>
</html>
When I click the button, an authentication popup windows appear, and once I authorize it, the function 'onGooglesuccess' runs, but it doesn't redirect to a page. I want it to redirect to a specific .aspx page where I can grab the code, replace it with a tokrn and grab user info.
How can I do that? I tried reading the docs on Google, but I just can't figure how to do it.
I'm developing my application in ASP.NET 4.5 / C# / Javascipt
I would like to pass a parameter to the jQuery document.ready() function from my View:
$(document).ready(function (parameter){
$('select[name=Product]').val(parameter);
});
How can I fire the event from my View and pass the parameter? I use Razor as View engine.
Thanks
You can't. The document.ready function doesn't take parameters. You could for example define this parameter as a global variable in your view:
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
</script>
and then in your separate javascript file use this global variable:
$(function() {
$('select[name=Product]').val(model.SomeProperty);
});
To avoid using global variables, you can define a closure and then returning this function to ready():
function start(parameter)
{
return function()
{
/*...use parameter */
alert('parameter: ' + parameter);
}
}
and then call ready():
$(document).ready(start('someValue'));
You can also define the start function in a external .js file and calling ready (for example) in your main html file.
Example:
external script.js:
function start(parameter)
{
return function()
{
/*...use parameter */
alert('parameter: ' + parameter);
}
}
html file:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<script>
$(document).ready(start('someValue'));
</script>
</head>
<body>
</body>
</html>
Calling ready() in the latter file allows you to pass server parameters to your functions. Example (using PHP. In this case you must change the extension from html to php to this file):
$(document).ready(start('<?php echo $serverParameter; ?>'));
You can effectively accomplish this with a closure. That is, if you are calling something like $(document).ready(startup) then you can easily rewrite startup so that you can call it with a parameter, e.g. $(document).ready(startup(7)). Pablo gave an excellent underrated answer, and it is worth giving a more detailed example.
Example
Here is a page which displays an alert, invoked by $(document).ready(), that calculates 6*9:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function startup() {
alert('6 * 9 = ' + 6 * 9);
}
</script>
</head>
<body>
Hello!
<script>
$(document).ready(startup);
</script>
</body>
</html>
Say you want to replace "9" with a variable parameter. The 4-step recipe to do this is:
Parameterize the function.
Wrap the function body in a closure. That is, return function() {...}.
Parameterize the body.
Call the function with the parameter.
Applying this to the above code:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function startup(x) { // Step 1 - Parameterize the function
return function() { // Step 2 - Put body in "return function() {...}"
alert('6 * '+x+' = ' + 6 * x); // Step 3 - Parameterize the body.
} // (closing brace for step 2)
}
</script>
</head>
<body>
Hello!
<script>
$(document).ready(startup(7)); // Step 4 - Call function with parameter.
</script>
</body>
</html>
This displays the alert "6 * 7 = 42".
What's Happening?
$(document).ready() takes as its parameter a function. This is why it is called in the first version above with just startup as the parameter. In contrast if you called it with startup() you wouldn't be passing in the startup function anymore, you would be passing in the return value of startup.
Since $(document).ready() takes a function as its parameter, that's what we give it: startup is transformed in the second version above into a function that returns a function, which has the parameter x set to the value we pass it initially. That is, startup(7) returns a function to $(document).ready() that has the value of x set to 7.
OP's Question
To specifically apply this to the OP's question, rewrite that call as
$(document).ready((function(x) { return function() {
$('select[name=Product]').val(x);
}})('name'));
where 'name' can be any other value that gets substituted for x. No need for global variables.
More information: JavaScript closures.
You can simply echo your parameter value into the Javascript code if its inline in your view.
$(document).ready(function (){
$('select[name=Product]').val('#ViewBag.Parameter');
});