I'm new to AngularJS and so far haven't had any problems until this one...
I am trying to display json data returned for my REST service call without any luck. I can hard-code in a data array into my controller script file and that will be displayed on my web page just fine however when trying to display my json data I'm not having any luck.
This is what I currently have coded...
Web page-
<div ng-controller="ExceptionLogDataController">
<div ui-grid="gridOptions" class="vertexGrid"></div>
</div>
ExceptionLogDataController-
$scope.vertexData = [];
$scope.gridOptions = {
enableSorting: true,
data: "vertexData",
columnDefs: [
{ name: 'Data Id', field: 'DataId' },
{ name: 'Source Date Time', field: 'SourceDateTime' },
{ name: 'Message Text', field: 'MessageText' },
{ name: 'IsDirty', field: 'IsDirty' }
// { name: 'FileName', field: 'FileName' },
// { name: 'GenJIRATicket', field: 'GenJIRATicket' },
// { name: 'MessageCount', field: 'MessageCount' },
// { name: 'MachineName', field: 'MachineName' },
// { name: 'AppDomainName', field: 'AppDomainName' },
// { name: 'ProcessName', field: 'ProcessName' },
// { name: 'StackTrace', field: 'StackTrace' }
],
};
//$scope.vertexData = [
// {
// "First Name": "John",
// "Last Name": "Smith",
// },
// {
// "First Name": "Jane",
// "Last Name": "Doe",
// }
//];
$scope.load = function () {
ExceptionLogDataFactory()
.then(function (response) {
$scope.vertexData = JSON.parse(response.data);
});
}
$scope.load();
}
ExceptionLogDataController.$inject = ['$scope', 'ExceptionLogDataFactory'];
ExceptionLogDataFactory-
var ExceptionLogDataFactory = function ($http, $q, SessionService) {
return function () {
var result = $q.defer();
$http({
method: 'GET',
url: SessionService.apiUrl + '/api/ExceptionLogData',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + SessionService.getToken() }
})
.success(function (response) {
result.resolve(response);
})
.error(function (response) {
result.reject(response);
});
return result.promise;
}
}
ExceptionLogDataFactory.$inject = ['$http', '$q', 'SessionService'];
I've verified that my REST call is returning JSON data through Postman so the problem lies with my front end code.
Making progress...
I'm getting my json object successfully returned and am trying to display it with the following...
$scope.data = [];
$scope.gridOptions = {
enableSorting: true,
data: 'data',
};
ExceptionLogDataService() //Call to Service that returns json object
.then(function (data) {
$scope.data = data;
$scope.gridOptions.data = $scope.data;
console.log($scope.data);
}
And this is the json object that is being returned via console.log call...
Object { DataId: 1074, SourceDateTime: "2016-01-19T13:29:01.2512456-05:00", MessageText: "There is an error in XML document (…", IsDirty: false, StatusList: Object, FileName: "D:\ProdMonitorSiteDev\ErrorFiles\…", GenJIRATicket: false, MessageCount: 1, MachineName: "VERTEXCUTIL01", AppDomainName: "", 2 more… }
This is the error that I am getting...
Error: newRawData.forEach is not a function
Well I figured it out!
I finally got my head out of the weeds and 'really' looked at the JSON object that was being returned from my service and noticed that the object was encapsulated with '{}' (curly braces) which is what was causing the newRawData.forEach error. So what I did was the following...
.then(function (data) {
$scope.data = "[" + JSON.stringify(data) + "]"; // 'Stringify my object and then encapsulate it with square brackets '[]' and then I could use JSON.parse to then parse the new string into a JSON object...
$scope.data = JSON.parse($scope.data);
// Worked like a champ!....
$scope.gridOptions.data = JSON.stringify($scope.data);
You don't need to parse the JSON.
$http.get(url)
.success(function (data) {
$scope.gridOptions.data = data;
}
This should work just fine for what you are doing.
Related
I am trying to use js grid for my application. I am trying to populate the grid after ajax request but it do not seem to work as expected.
I am trying with SQL Server as back end and web application is asp.net MVC
This is my code in the html
var table;
var result;
var $j = jQuery.noConflict();
$j(document).ready(function () {
table = $j('#grid').jsGrid({
height: "60%",
width: "50%",
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
controller: {
loadData: function (filter) {
var d = $j.Deferred();
$j.ajax({
type: "POST",
contentType: "application/json",
url: "#Url.Action("LoadData", "User")",
datatype: "json",
data: filter
#*success: function (data) {
result = data.data;
console.log("result", result);
d.resolve(result)
},
error: function (data) {
window.location.href = '#Url.Action("Error", "Audit")';
}*#
}).done(function (data) {
console.log("response", data);
console.log("data.data", data.data);
d.resolve(data)
});
return d.promise();
},
fields: [
{ name: "LastName", type: "text"},
{ name: "FirstName", type: "text"},
{ name: "Email", type: "email"},
{ name: "PhoneNumber", type: "number"},
{ type: "control" }
]
}
});
});
In Controller I return
''return Json(new { data }, JsonRequestBehavior.AllowGet);''
I expect the json data to bind in the div. But it did not ? Thanks
Ok, so I've had this problem recently.
First off, change your "height" to px, auto, or get rid of it entirely. It's not doing what you think it's doing.
Next, since you have paging, you need to return your data in the following format:
{
data: [{your list here}],
itemsCount: {int}
}
It's barely in the documentation, as it's inline and not very obvious. (Bolding mine.)
loadData is a function returning an array of data or jQuery promise that will be resolved with an array of data (when pageLoading is true instead of object the structure { data: [items], itemsCount: [total items count] } should be returned). Accepts filter parameter including current filter options and paging parameters when
http://js-grid.com/docs/#controller
I am trying to set table values from webservice response.
Iam getting my web service response like this.but if he response is like this means it is not getting set there.This response can be dynamic.
0:{name: "image.png", base64: "iVBORw"}
1:{name: "download.png", base64: "iVBO"}
2:{name: "test-animation.gif", base64: "R0lGODlhLAEs"}
How can i change it to??
[["image.png", "iVBORw"],["download.png", "iVBO"],[test-animation.gif", "R0lGODlhLAEs"]]
here it is what iam trying
$.cordys.ajax({
method: "somewebservice",
namespace: "Package",
parameters: {
emailid:mailidvalue
},
dataType: '* json',
success: function (result) {
output=result;
bodycontent=output["data"]["body"];
var attachvalue=result.data.tuple;
$('#attachmenttable').DataTable( {
"data": attachvalue,
columns: [
{ title: "File Name" },
{ title: "Base64" }
]
} );
},
error: function(err){
console.log(err);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
I see a 1-1 mapping between what you are given and what you desire, therefore use Array.prototype.map() or $.map.
var given = {
0: {
name: "image.png",
base64: "iVBORw"
},
1: {
name: "download.png",
base64: "iVBO"
},
2: {
name: "test-animation.gif",
base64: "R0lGODlhLAEs"
}
};
var desired = Object.keys(given).map(function(key) {
return [ given[key].name, given[key].base64 ];
});
console.log(desired);
var given = {
0: {
name: "image.png",
base64: "iVBORw"
},
1: {
name: "download.png",
base64: "iVBO"
},
2: {
name: "test-animation.gif",
base64: "R0lGODlhLAEs"
}
};
var desired = $.map(given, function (value, key) {
return [[ given[key].name, given[key].base64 ]];
});
console.log(desired);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am trying to create a ui-grid with some DDL filter (from get data). If I try with async: false, all works perfectly. This is the call:
var Documents = [];
var solutionSetColumn = {};
var solutionSetFilters = [];
LoadData = function () {
Documents = [];
$.ajax({
type: "POST", url: url,
success: function (data) {
Documents = data.d;
},
error: function (err) {
}
});
}
}
$.ajax({
type: "POST", url: url,
success: function (data) {
solutionSetColumn = { field: 'SolutionSet', displayName: 'Solution Set', width: 190, filter: { type: uiGridConstants.filter.SELECT, selectOptions: data.d } };
},
error: function (err) {
solutionSetColumn = { field: 'SolutionSet', displayName: 'Solution Set', width: 190 }
}
});
LoadData();
gridOptions = {
enableHorizontalScrollbar: 2,
enableVerticalScrollbar: 0,
enableFiltering: true,
data: Documents,
columnDefs: [
{ field: 'Name', displayName: 'Nome File', width: 200 },
solutionSetColumn
]
}
$scope.gridOptions = gridOptions;
});
How to get all async without gridOption error like colDef undefined? Obviously without the setTimeout! Thanks
You need to move your $scope.gridOptions (and the options definition) into the success path of your ajax call.
I am trying to create dynamic listbox values but getting this error in console:
Uncaught TypeError: Cannot assign to read only property 'active' of [
Here's my code( pasting only the code for listbox ):
body: [
{
type: 'listbox',
name: 'type',
label: 'Panel Type',
value: type,
'values': get_author_list(),
tooltip: 'Select the type of panel you want'
},
]
.....
And I am calling this function to get dynamic list...
function get_author_list() {
var d = "[{text: 'Default', value: 'default'}]";
return d;
}
I am guessing that the values in listbox only takes static var and not dynamic. But I need to insert dynamic values in this list. Please can anyone help me find a workaround. Is there any possibility to insert via ajax?
Thanks, in advance!!
I needed something similar for .NET site. Even though is not great code I hope it can help someone.
tinymce.PluginManager.add('DocumentSelector', function (editor, url) {
// Add a button that opens a window
editor.addButton('DocumentSelector', {
text: 'Document',
icon: false,
title: "Document Selector",
onclick: function () {
var _documentList;
//load all documents
var _data = JSON.stringify({/* Some data */});
$.ajax({
type: "POST",
url: "/api/TinyMCE/GetDocuments",
data: _data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data) {
_documentList = eval('(' + data + ')');
// Open window
editor.windowManager.open({
title: 'Document Selector',
body: [
{
type: 'listbox',
name: 'DocURL',
label: 'Documents',
values: _documentList
},
{
type: 'textbox'
, name: 'TextToDisplay'
, value: _text
, label: 'Text To Display'
},
{
type: 'textbox'
, name: 'TitleToDisplay'
, value: _title
, label: 'Title'
},
{
type: 'listbox',
name: 'TheTarget',
label: 'Target',
values: [{ text: 'None', value: "_self" }, { text: 'New Window', value: "_blank" }],
value: _target
}
],
onsubmit: function (e) {
// Insert content when the window form is submitted
}
});
},
error: function (xhr, status, error) {
alert("Error! " + xhr.status + "\n" + error);
}
});
}
});
});
And here it is some of the Behind code
public class TinyMCEController : ApiController
{
public class DocumentsInfo
{
// Some data
}
public class DocumentList
{
public string text { get; set; }
public string value { get; set; }
}
[HttpPost]
[ActionName("GetDocuments")]
public object GetDocuments(DocumentsInfo docInfo)
{
//Test data
List<DocumentList> _DocumentList = new List<DocumentList>();
_DocumentList.Add(new DocumentList {
text = "Document1.pdf",
value = "value1"
});
_DocumentList.Add(new DocumentList
{
text = "Document2.pdf",
value = "value2"
});
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(_DocumentList);
return json;
}
}
I have a joomla site running k2 and pulling info from it by adding format=json to the end of the string: https://www.example.com/posts?format=json which outputs something like this:
{
site: {
url: "https://www.example.com",
name: "mySite"
},
category: {
id: "67",
name: "Gauteng",
alias: "gauteng",
link: "/tna/provincial/gauteng.html",
parent: "66",
extraFieldsGroup: "0",
image: null,
ordering: "1",
events: {
K2CategoryDisplay: ""
},
chidlren: []
},
items: [{
id="1",
title="The Title",
body="body content here..."
},
{
id="2",
title="The Title",
body="body content here..."
}
}
now i am creating a service for this and just want to access "items".
.factory('Posts', function($http) {
var posts = [];
return {
getPosts: function(){
return $http.get("https://www.example.com/posts?format=json").then(function(response){
posts = response;
return posts;
});
},
getPost: function(index){
return posts[index];
}
}
});
it doesnt seem to be working though. is there any way to access just "items" with the call?
You post syntax should be posts = response.data.items
return $http.get("https://www.example.com/posts?format=json").then(function(response){
posts = response.data.items; //items here
return posts;
});