This is my function to fetch the array.
$scope.getclinicofuser = function()
{
var dataParameter = {
"primaryEmailId":$scope.data1.email
}
$http({
url: "/cms/api/user/getUserClinic",
method: "POST",
headers :{'Content-Type': 'application/json','Accept': 'application/json' },
data: dataParameter
}) .success(function(response) {
$scope.DomainName = response;
console.log($scope.DomainName);
});
};
});
Here is the api call response
{
"clinicNames": [2]
0: {
"clinicName": "testing"
"DomainName": "Aman.example.com"
"primaryEmailId": "example#gmail.com"
}-
1: {
"clinicName": "test-clinic"
"DomainName": "raman.example.com"
"primaryEmailId": "example#gmail.com"
}-
-
"status_code": "success"
}
My html tag
<li ng-repeat="response in DomainName">{{root.clinicNames}}</li>
Now what i want to do is to display BOTH DomainName in HTML i had a hussel with HTML ng-repeat tags but still no clues what i am doing wrong
Try
<li ng-repeat="response in DomainName.clinicNames track by $index">{{response.DomainName}}</li>
Related
I'm a newbie when it comes to javascript. I'm using the jsGrid plugin to display a grid in the browser. The grid column headers will have the values "Request Status" and "Request Id". I can make it work with static data.
(function() {
var adminDashboardController = {
loadData: function(filter) {
return $.grep(this.requests, function(request) {
return (!filter.Status || request.Status === filter.Status)
&& (!filter.RequestId || request.RequestId.indexOf(filter.RequestId) > -1)
});
},
insertItem: function(insertingReq) {
},
updateItem: function(updatingReq) {
},
deleteItem: function(deletingReq) {
}
};
window.adminDashboardController = adminDashboardController;
adminDashboardController.status = [
{ Name: ""},
{ Name: "Requested"},
{ Name: "Declined"}
];
//This is the static data
adminDashboardController.requests = [
{ "Status": "Requested", "RequestId": "1"},
{ "Status": "Declined", "RequestId": "2"}
];
}());
But when it comes to fetching the data from an ajax call (using a json file for testing as the data source), the data no longer gets filtered when I choose "Requested" or "Declined" as the filtering criterion. I'm using the format mentioned in the documentation like this -
(function() {
var adminDashboardController = {
loadData: function (filter) {
return $.ajax({
type: "GET",
dataType: "json",
url: "/json/db514.json",
data: filter
});
},
insertItem: function(insertingReq) {
},
updateItem: function(updatingReq) {
},
deleteItem: function(deletingReq) {
}
};
adminDashboardController.status = [
{ Name: ""},
{ Name: "Requested"},
{ Name: "Declined"}
];
}());
I can't understand how to implement the filtering in this case!
The reason is that filtering should be implemented in the code.
In general it can be done:
on the client (just as in your first sample)
on backend, then you have to pass the filter to your endpoint, which will do filtering and return data.
combined approach (partially on backend and after on the client)
In your case you could either add an endpoint on backend, which will load json and filter data, or still do filtering on client-side, for example:
loadData: function (filter) {
return $.ajax({
type: "GET",
dataType: "json",
url: "/json/db514.json"
}).then(function(requests) {
return $.grep(requests, function(request) {
return (!filter.Status || request.Status === filter.Status)
&& (!filter.RequestId || request.RequestId.indexOf(filter.RequestId) > -1)
});
});
}
Checkout this issue on GtiHub https://github.com/tabalinas/jsgrid/issues/32.
I have got back response at this line in form of json from web api controller action:
var json = await response.Content.ReadAsStringAsync();
The short version of the response is something like this:
{
"Response": {
"ResponseStatus": 1,
"Error": {
"ErrorCode": 0,
"ErrorMessage": ""
},
"TraceId": "83b04f8c-f7dd-4755-9767-b0c861ea9e28",
"Origin": "DEL",
"Destination": "BOM",
"Results": [
[{
"ResultIndex": "OB12",
"Source": 6,
"Fare": {
"Currency": "INR",
"OtherCharges": 58.29,
"ChargeBU": [{
"key": "TBOMARKUP",
"value": 8.29
}, {
"key": "CONVENIENCECHARGE",
"value": 0
}, {
"key": "OTHERCHARGE",
"value": 50.00
}],
"Discount": 0,
},
}]
]
}
}
The full version is shown at http://pastebin.com/eEE72ySk
Then i am returning back HttpResponse from webApi Controller by sending this json var data to CreateResponse method and returning back res like this:
HttpResponseMessage res = Request.CreateResponse(HttpStatusCode.OK, json);
return res;
I have to return back this res to $.ajax function on view page:
$.ajax(
{
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({ 'TokenId': $("#pageInitCounter").val()}, true),
success: function (data) {
alert(data);
var items = [];
$.each(data, function (key, val) {
items.push(key + ' : ' + val + '</br>');
});
}
});
I can see the whole content in alert box.
I want to know how to loop through each and every data i got back and assign their values to the respective <div> elements on the view page. The Response which i got back contains several arrays and arrays into arrays. I am confused how to manage each and every data.
Arrays are accessed with indexers and for an array containing an array, you use
XXX[0][0].YYY
to access the first array within the first array.
The code to access some of your properties would be
$.ajax(
{
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({ 'TokenId': $("#pageInitCounter").val()}, true),
success: function (data) {
var responseStatus = data.Response.ResponseStatus; // returns 1
var errorCode = data.Response.Error.ErrorCode; // returns 0
var origin = data.Response.Origin; // returns 'DEL'
var resultIndex = data.Response.Results[0][0].ResultIndex; // returns 'OB12'
}
});
Most of the data in the arrays seems to contain only one object, or one array containing one object and if that is always the case, then accessing it using [0] or [0][0] will be fine.
For the arrays containing multiple objects such as data.Response.Results[0][0].Fare.ChargeBU, you can use a for loop or $.each() loop, for example
$.each(data.Response.Results[0][0].Fare.ChargeBU, function (index, chargeBU) {
var key = chargeBU.key // returns "TBOMARKUP", "CONVENIENCECHARGE", "OTHERCHARGE"
});
Try This
{
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({ 'TokenId': $("#pageInitCounter").val()}, true),
success: function (data) {
alert(data);
var items = [];
$.each(data.Response.Results, function (key, val) {
items.push(key + ' : ' + val + '</br>');
});
}
};
I want to create a JSON string in the following format as below using AngularJS:
{
"userid": 100,
"fleetid": 506,
"comments": "This is a test comment",
"fleetcheckdate": "29/10/1976",
"options": [{
"fleetcheckid": "1",
"fleetcheckvalueid": "1"
}, {
"fleetcheckid": "2",
"fleetcheckvalueid": "1"
}, {
"fleetcheckid": "3",
"fleetcheckvalueid": "1"
}]
}
Where
"userid"
"fleetid"
"comments"
"fleetcheckdate"
are all separate values know to me.
For "options" I have a multi-dimensional array that stores the values for "fleetcheckid" and "fleetcheckvalueid" that I create as follows:
$scope.selectedRadioArray = [];
$scope.doSomething = function(fleetCheckItemID, fleetCheckID)
{
$scope.selectedIDS = [fleetCheckItemID, fleetCheckID];
$scope.selectedRadioArray.push($scope.selectedIDS);
console.log("Array: " + $scope.selectedRadioArray); // Prints e.g. 4,3,8,6,34,8
}
The doSomething() method is fired each time the user interacts with a button and this generates the 2 values "fleetcheckid" and "fleetcheckvalueid". In the example above the user has clicked the button 3 times. The button can be clicked any number of times.
How do I convert the information above into a JSON string as per the example that I can send to my Database via a $http.post()?
When sending information to the server via $http, it's generally a good idea to use JSON. Don't convert it to a string.
Simply format your payload like this:
var payload = {
userId: $scope.userId,
/* etc.... */
options: $scope.optionsArray
};
Then, when sending to the server, do this:
$http.post('path/to/api', payload, { headers: { /* etc... */ }}).then(successCallback).catch(errorCallback);
you can use in the $http someething like this
$http({
url: uri,
method: 'post',
data: angular.toJson(categoria),
headers: {
'Authorization': 'Bearer ' + token.data.access_token,
'Content-type': 'application/json'
}
}).then(function successCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
}, function errorCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
});
in this case `angularToJson` convert it on a JSON and send it in the body
I've tried searching through StackOverflow regarding this issue but could not find a solution that worked for me. I'm using AngularJS. I have simple controller that calls a http service and reads the response data. In this specific case, I have a JSON output with an objects array I am unable to read.
Here's the JSON output:
{
"results": [{
"id": "1",
"download_url": "",
"uploader": {
"id": "114899"
},
"uploaded": "1442599380",
"streaming_url_timeout": 1446092554
}, {
"id": "2",
"download_url": "",
"uploader": {
"id": "114899"
},
"uploaded": "1442599380",
"streaming_url_timeout": 1446092554
}]
}
I'm trying to get access to items in 'results'. This is my Service that retrieves the JSON data:
this.getUData = function() {
var deferred = $q.defer();
$http.jsonp(API_URL + 'udata')
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
}
And then this is how i call this service from my controller:
myservices.getUData().then(function(data) {
$scope.uitems = data.results;
});
Template:
<div class="item" href="#" ng-repeat="item in uitems">
<h2>{{item.id}}</h2>
</div>
But when I try to access the items in 'results', I get the following error:
Uncaught SyntaxError: Unexpected token :
The line in question for this error is "results":[
Looks like in this case the callback function was not working correctly on the PHP server so I managed to get away by using the 'GET' method in the $http service like so:
this.getUData = function() {
var deferred = $q.defer();
$http({method: 'GET', url: API_URL + 'udata'})
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
}
I have a div which I would like to fill with a jsTree:
I get the "Loading" icon where the tree is meant to display, however, there would seem to be a javascript error, even though one is not thrown.
I load my folder structure from an AJAX Request as follows. The Documents.aspx/GetFolders Web Method returns a List containing FolderId, ParentId & Folder Name. I have debugged the web method and it is passing the correct results to the jsTree "data" function.
$.ajax({
type: "POST",
url: 'Documents.aspx/GetFolders',
contentType: "application/json; charset=utf-8",
success: function (data) {
data = data.d;
$("#tree").jstree({
"core": {
"themes": {
"responsive": true
},
"data": function () {
var items = [];
items.push({ 'id': "jstree_0", 'parent': "#", 'text': "Documents" });
$(data).each(function () {
items.push({ 'id': "jstree_" + this.DocumentFolderId, 'parent': "jstree_" + this.ParentId, 'text': "" + this.Name });
});
return items;
}
},
"types": {
"default": {
"icon": "fa fa-folder icon-lg"
},
},
"plugins": ["contextmenu", "dnd", "state", "types"]
});
},
error: function () {
toastr.error('Error', 'Failed to load folders<span class=\"errorText\"><br/>There was a fatal error. Please contact support</span>');
}
});
After debugging the code, it seems the data is being retrieved correctly and is returning the object array as intended.
Is there are any problem with the above (or is there somewhere else I should be looking)? Or is there a better method of achieving its intended purpose?
I think I have finally found the answer! :)
"core": {
"themes": {
"responsive": true
},
"data": {
type: "POST",
url: "Documents.aspx/GetFolders",
contentType: "application/json; charset=utf-8",
success: function (data) {
data.d;
$(data).each(function () {
return { "id": this.id };
});
}
},
}
Server side, you need to return the data in the array format required, i.e:
[{id = "node0", parent = "#", text = "Documents"},
{id = "node1", parent = "node0", text = "Public"},
{id = "node2", parent = "node0", text = "Restricted"}]
Just in case anyone has the "loading..." issue, this format fixed it for me when returning data.
[{"id":"node0", "parent":"#", "text":"Documents"},
{"id":"node1", "parent":"node0", "text":"Public"},
{"id":"node2", "parent":"node0", "text":"Public"}]