I am trying to make put call in angular js after selecting value from dropdown selection. I already got value from selection. Just want too make put call but not able to make response.
Here is HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angular.js#1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.js"></script>
<script data-require="jquery#1.8.3" data-semver="1.8.3" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="sensorsCtrl">
<span class="sensors actionable u-mv" id="myid" ng- click="addSequenceLink()">
Add Sequence Link
</span>
<div ng-show="innerIsIsLoading" style="position: fixed; z-index: 999999; top: 450px; left: 65%">
<px-spinner size="50"></px-spinner>
</div>
<div>
<select ng-model="asset1" id="assetNameGroup" ng-change="changedValue(asset1)" ng-options="x.name for x in Nameitems track by x.uri">
<option>Select Name</option>
</select>
<select ng-model="asset2" id="assetNameGroup2" ng-change="sectionChangedValue(asset2)" ng-options="x.name for x in asset1.sections">
<option value="">Select Name</option>
</select>
<select ng-model="asset3" id="assetNameGroup3" ng-change="positionChangedValue(asset3)" ng-options=" x.sensorPositionName for x in asset2.ultrasonicSensorPositions">
<option value="">Select Name</option>
</select>
{{positionItem}}
</div>
</body>
</html>
javascript
console.clear();
var app = angular.module("myApp", []);
app.controller('sensorsCtrl', function($scope, $window, $timeout, $http{
$scope.innerIsIsLoading = true;
$http.get('sample.json').success(function(resp) {
$scope.innerIsIsLoading = false;
$scope.assetData = resp;
$scope.Nameitems = [];
var testobj = $scope.assetData[0].name;
angular.forEach($scope.assetData, function(val, key) {
$scope.Nameitems.push({
"name": val.name,
"uri": val.uri,
"sections": val.sections
});
});
});
$scope.itemList= [];
$scope.sectionItem = [];
$scope.positionItem = [];
$scope.changedValue = function(item){
$scope.itemList.push(item.sections);
}
$scope.sectionChangedValue = function(item){
$scope.sectionItem.push(item.ultrasonicSensorPositions)
}
$scope.positionChangedValue = function(item){
$scope.positionItem.push(item)
}
$scope.onclick= function(currentUlSensor){
var req = {
method: 'PUT',
url: xyz,
headers: {
'Content-Type': 'application/json'
},
data: $scope.positionItem;
}
$http(req).success(function (response) {
$scope.isLoading = false;
$scope.xyz= response;
});
}
});
Data should be from last drop down section data make put call and request data is like this
[
{
"ultrasonicSensorPositionId": 18,
"sensorPositionName": "ultrasonic sensor position 1",
"diameter": 22.5,
"rotation": 90,
"sequenceNumber": 1,
"sectionId": "/assets/332008d3-fddc-391b-9cc1-6a41f7ff73d1"
},
{
"ultrasonicSensorPositionId": 19,
"sensorPositionName": "ultrasonic sensor position 2”,
"diameter": 22.5,
"rotation": 90,
"sequenceNumber": 2,
"sectionId": "/assets/332008d3-fddc-391b-9cc1-6a41f7ff73d1"
}
]
here is plunker demo .
Your request seems to be OK - just remove the ; from data: $scope.positionItem;. I usually use:
$http({
url: xyz,
method: 'PUT',
contentType: 'application/json; charset=utf-8',
data: $scope.positionItem
}).then(function (result) { // this is the success
...
}, function (error) { // this is the error
....
});
Related
I'm working on a Javascript function that will set a kendo.data.HierarchicalDataSource object using a url that fetches the data. At the end of this function, if the data source actually has data, I want to set a treeview with the data (which is already working). If it doesn't have data, instead of setting the treeview, I want to make a label visible that tells the user that there is no data.
My problem: How to I determine that there is/isn't data in the HierarchicalDataSource? When I try call any function or get any property of getData, it returns undefined.
function loadTreeGroupData(applicationId) {
var treeview = $("#treeview-kendo").data("kendoTreeView");
var url = $('#urlHolders').data("gettreeUrl");
var appId = 0;
if (applicationId != undefined && applicationId != "")
appId = applicationId;
var getData = new kendo.data.HierarchicalDataSource({
change: function (e) {
for (var i = 0; i < e.items.length; i++) {
e.items[i].load();
}
},
transport: {
read: {
url: url, //"GetAlertsTree",
dataType: "json",
contentType: "application/json",
data: { applicationId: appId }
}
},
schema: {
model: {
id: "id",
hasChildren: "hasChildren",
children: "measureGroups"
}
}
});
if (/*the treeview has data*/) {
treeview.setDataSource(getData);
} else {
/*set a label that tells the user that there's no data*/
}
}
I would suggest you to do the following changes in your code:
Set the HierarchycalDataSource at the treeView initialization, instead of add it later;
Declare treeView's div and label as display:none or whatever the way you hide them;
Use DataSource's requestEnd event to show/hide the elements.
<!DOCTYPE html>
<html>
<head>
<base href="https://demos.telerik.com/kendo-ui/treeview/remote-data-binding">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2021.2.616/styles/kendo.default-v2.min.css" />
<script src="https://kendo.cdn.telerik.com/2021.2.616/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2021.2.616/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div class="demo-section k-content">
<div id="treeview" style="display: none"></div>
<div id="no-data-label" style="display: none">No data found</div>
</div>
<script>
var serviceRoot = "https://demos.telerik.com/kendo-ui/service";
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot + "/Employees",
dataType: "jsonp"
}
},
schema: {
model: {
id: "EmployeeId",
hasChildren: "HasEmployees"
}
},
requestEnd: (e) => {
if (e.response && e.response.length) {
$("#treeview").show();
$("#no-data-label").hide();
}
else {
$("#treeview").hide();
$("#no-data-label").show();
}
}
});
$("#treeview").kendoTreeView({
dataSource: homogeneous,
dataTextField: "FullName"
});
</script>
</div>
</body>
</html>
Dojo
The ngTable document does not provide complete information and sample codes and hard to follow. I managed to make bellow code to fetch and display a table from server dynamically. But when I click the table header to sort, the getData (and so the $http) is triggered again, and the result is that after click, the column is not sorted, but the displayed data doubled itself horizontally (say, when open the page, the displayed columns are [id, name], after the click on a column of the table header, it becomes [id, name, id, name]).
<!DOCTYPE html>
<html>
<head lang="en">
<title><%= title %></title>
<meta charset="utf-8">
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="bower_components/ng-table/ng-table.min.js"></script>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="bower_components/ng-table/ng-table.min.css" />
<script>
(function () {
'use strict';
let app = angular.module('myApp', ['ngTable']);
app.controller('demoCtrl', ['$http', 'NgTableParams', function ($http, NgTableParams) {
let ctrl = this;
ctrl.cols = [];
ctrl.rows = [];
ctrl.tableParams = new NgTableParams({}, {
getData: function (params) {
ctrl.xhr = $http({
method: 'GET',
url: '/ng-table-demo/test_data',
}).then(function (rsp) {
let cols = Object.keys(rsp.data[0]);
for(let i = 0; i < cols.length; i++) {
ctrl.cols.push({field: cols[i], title: cols[i], sortable: cols[i], show: true});
}
ctrl.rows = rsp.data;
return ctrl.rows;
}, function (rsp) {
console.log('http failed.');
});
return ctrl.xhr;
}});
}]);
})();
(function () {
"use strict";
angular.module("myApp").run(configureDefaults);
configureDefaults.$inject = ["ngTableDefaults"];
function configureDefaults(ngTableDefaults) {
ngTableDefaults.params.count = 5;
ngTableDefaults.settings.counts = [];
}})();
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="demoCtrl as ctrl" class="container-fluid">
<h2>ng-table-demo</h2>
<table ng-table-dynamic="ctrl.tableParams with ctrl.cols" class="table table-condensed table-bordered table-striped">
<tr ng-repeat="row in $data">
<td ng-repeat="col in $columns">{{row[col.field]}}</td>
</tr>
</table>
</div>
</body>
</html>
I tried to surround the ctrl.xhr block with bellow, then it stops to duplicate but the sort does not happen anyway.
if(ctrl.xhr === undefined) {
ctrl.xhr = $http...;
}
return ctrl.xhr;
What mistake(s) I made?
The workaround is abandon of getData and set the dataset on xhr succeeded. bellow code worked.
(function () {
'use strict';
let app = angular.module('myApp', ['ngTable']);
app.controller('demoCtrl', ['$http', 'NgTableParams', function ($http, NgTableParams) {
let ctrl = this;
ctrl.cols = [];
$http({
method: 'GET',
url: '/ng-table-demo/test_data',
}).then(function (rsp) {
let cols = Object.keys(rsp.data[0]);
for (let i = 0; i < cols.length; i++) {
ctrl.cols.push({
field: cols[i],
title: cols[i],
sortable: cols[i],
show: true
});
}
ctrl.tableParams = new NgTableParams({}, {
dataset: rsp.data
});
}, function (rsp) {
console.log('http failed.');
});
}]);
})();
Still, I don't know how getData works.
We have a very simpel Google Apps Script Web App, which purpose is to show JSON data in a HTML drop-down-list. The JSON file exists in Google Drive. Inspiration code from: http://jsfiddle.net/manoj_admlab/Mta5b/3/
But when we are trying to 'Fetch Json' no data is loaded in to the dropdown-list:
index.html
<!DOCTYPE html>
<html>
<br> <br>
<center>
<head>
<base target="_top">
</head>
<body>
<select id="destinations">
<option value="">Select</option>
</select>
Fetch JSON
</center>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
google.script.run.getJson(); // Runs the function "getJson();" in Code.gs
$('#fetch').click(function(s) {
$.post(s, {json: JSON.stringify(json)}, function(data) {
$.each(data.Destinations, function(i, v) {
$('#destinations').append('<option value="' + v.destinationID + '">' + v.destinationName + '</option>');
});
});
});
</script>
</body>
</html>
Code.gs
function doGet() {
var template = HtmlService.createTemplateFromFile('index');
var htmlOutput = template.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}
function getJson() {
var files = DriveApp.getFilesByName("jsonData.json");
var file = files.next();
var JSONDATA = file.getAs("application/json").getDataAsString();
//JSONDATA = JSON.stringify(JSONDATA);
JSONDATA = JSON.parse(JSONDATA);
Logger.log(JSONDATA);
click(JSONDATA); // <-- Trying to pass this data to "$('#fetch').click(function(s) {"
}
jsonData.json
{
"options": {
"Destinations": [
{
"destinationName": "London",
"destinationID": "lon"
},
{
"destinationName": "New York",
"destinationID": "nyc"
},
{
"destinationName": "Paris",
"destinationID": "par"
},
{
"destinationName": "Rome",
"destinationID": "rom"
}
]
}
}
You have to return the data in getJson() function, and when calling it, you need to pass a callback, with withSuccessHandler(), as such:
in HTML:
function justLog(e){
console.log(e);
}
$('#fetch').click(function(s) {
google.script.run.withSuccessHandler(justLog).getJson(); // Runs the function "getJson();" in Code.gs
});
in code.gs, finish the function with:
return JSONDATA;
Thanks Kriggs! This worked out great:
Index.html:
<!DOCTYPE html>
<html>
<head>
<select id="dropDownDest">
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
function onSuccess(json) {
$.each(json.Cars, function (key, value) {
$("#dropDownDest").append($('<option></option>').val(value.carID).html(value.CarType));
});
$('#dropDownDest').change(function () {
alert($(this).val());
//Code to select image based on selected car id
});
}
google.script.run.withSuccessHandler(onSuccess)
.jsonData();
</script>
</head>
</html>
Code.gs:
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function jsonData() {
var a = {
Cars: [{
"CarType": "BMW",
"carID": "bmw123"
}, {
"CarType": "mercedes",
"carID": "merc123"
}, {
"CarType": "volvo",
"carID": "vol123r"
}, {
"CarType": "ford",
"carID": "ford123"
}]
};
Logger.log(a);
return a;
}
I am having issues getting the ng-repeat to walkthrough my JSON response, I am new to AngularJS so I am sure its a newbie mistake :). I am trying to have the ng-repeat go through the ns0:AttributeDetails, ns0:Attributes. Here is the JSON data:
{"ns0:GetAgentProfile.Response": {
"xmlns:ns0": "http://URL",
"ns1:Header": {
"xmlns:ns1": "http://URL",
"xmlns:ns7": "http://URL",
"ns1:Source": null,
"ns1:CreatedDateTime": "2014-03-24T09:34:28.339-05:00",
"ns1:MessageType": "Request",
"ns1:MessageId": null
},
"ns0:ProfileDetails": {
"ns0:UserIdentifier": {
"ns0:UserGUID": "2BCF0074-392F-4653-8733-02063C2DBC5C",
"ns0:UserName": "Username01"
},
"ns0:AttributeDetails": {"ns0:Attribute": [
{
"ns0:Name": "AgentLogin",
"ns0:Value": ["Username01"]
},
{
"ns0:Name": "FullName",
"ns0:Value": ["Name, User"]
},
{
"ns0:Name": "LanguageSpoken",
"ns0:Value": ["English|Chinese"]
},
{"ns0:Name": "Supervisor"},
{
"ns0:Name": "Region",
"ns0:Value": ["Region01"]
},
{
"ns0:Name": "Country",
"ns0:Value": ["CO"]
},
{
"ns0:Name": "ClientAccessGroup",
"ns0:Value": ["CountryMobileCCR"]
},
{"ns0:Name": "Roles"}
]},
Here is the HTML:
<!DOCTYPE html>
<html ng-app="auth" xmlns="http://www.w3.org/1999/html">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script src="js/bootstrap.js"></script>
<script src="js/angular.js"></script>
<script src="js/authorization.js"></script>
</head>
<body ng-controller="MainCtrl">
<div>
<div class="container-fluid">
<form class="well">
<label>Username:</label>
<input><br><br>
<button ng-click="getData()" class="btn btn-primary">Submit</button>
<button ng-click="clearData()" class="btn btn-danger">Reset</button>
</form>
</div>
<h1>Response from Service:</h1>
<!-- <pre>{{data | json}}</pre> -->
<pre>
Username: {{data['ns0:GetAgentProfile.Response']['ns0:ProfileDetails'] ['ns0:UserIdentifier']['ns0:UserName']}} <br>
Profile Details</pre>
<div ng-repeat="Attribute in data">{{ data['ns0:GetAgentProfile.Response']['ns0:ProfileDetails']['ns0:AttributeDetails']['ns0:Attribute']['ns0:Name'] }}</div>
</div>
</html>
Here is the JS for the controller fetching the data:
var app = angular.module('auth', []);
app.factory('authService', function($http) {
var promise;
var authService = {
async: function() {
if ( !promise ) {
promise = $http.get('package.json').then(function (response) {
console.log(response);
return response.data;
});
}
return promise;
}
};
return authService;
});
app.controller('MainCtrl', function( authService,$scope) {
$scope.clearData = function() {
$scope.data = {};
};
$scope.getData = function() {
authService.async().then(function(d) {
$scope.data = d;
});
};
});
Again I apologize for the newbie question. Any assistance would be greatly appreciated.
Drill down to your array in the repeat directive:
<div ng-repeat="Attribute in data.ns0:GetAgentProfile.Response.ns0:ProfileDetails.ns0:AttributeDetails.ns0:Attribute">
And now you can do:
{{Attribute.ns0:Name}} and {{Attribute.ns0:Value}}
Not sure if the : will play nicely tho, may have to escape those.
I am having trouble trying to append a new url parameter after selecting a genre to create a request to the API.
My ng-change is genreChange. When it been selected, it should automatically append the new url parameter like this &with_genre=fiction in the $scope.movies url before submitting the form with submitButton
<form ng-submit="submitButton()" name="cForm" class="form-horizontal">
<h2>Discover the gems</h2>
<div class="form-group">
<select class="form-control" ng-model="genreSelect" ng-change="genreChange()">
<option ng-repeat="genre in genreList.genres" value="{{genre.id}}">{{genre.name}}</option>
</select>
</div>
<input type="submit" value="hello" />
</form>
-
$scope.genreChange = function() {
$scope.genreVar = $scope.genreSelect;
$scope.movies.get({with_genres: $scope.genreVar});
}
$scope.movies = $resource('http://api.themoviedb.org/3/discover/movie:action', {
api_key: apikey,
callback: 'JSON_CALLBACK'
}, {
get: {
method: 'JSONP'
}
});
$scope.submitButton = function() {
$scope.films = $scope.movies.get();
}
I am doing this method just in case a user leaves it blank.
Thanks
This is what Resource.bind does.
var MovieResource = $resource('http://api.themoviedb.org/3/discover/movie:action', {
api_key: apikey,
callback: 'JSON_CALLBACK'
}, {
get: {
method: 'JSONP'
}
});
$scope.movies = MovieResource;
$scope.genreChange = function() {
$scope.genreVar = $scope.genreSelect;
$scope.movies = MovieResource.bind({with_genres: $scope.genreVar})
}
$scope.submitButton = function() {
$scope.films = $scope.movies.get();
}