Parse Json to use in a dojo widget? - json

I am newbie to dojo and json. I am trying to Query the server to get data as json and parse the result and use html template in a widget to display.
To test it I tried this.
require(["dojo/request", "dojo/dom", "dojo/dom-construct","dojo/_base/array", "my/widgets/", "dojo/domReady!"],
function(request, dom,domConst, arrayUtil, support){
// Load up our authors
request("js/my/data/sample.json", {
handleAs: "json"
}).then(function(LinksMap){
// Get a reference to our container
arrayUtil.forEach(LinksMap, function(List){
// Create our widget and place it
console.debug(LinksMap);
//var widget = new support(author).placeAt(authorContainer);
Not sure if I am doing it right. Is there anything I am misssing. I am following the example as provided here and building on it.

I think from the comments on your post you want to modified the deferred handling function to be
request("js/my/data/sample.json", {
handleAs: "json"
}).then(function(jsonResults){
console.log(jsonResults.Result)
});
The json you posted is an object with a property Result. The Result property contains an array of objects. Those objects then contain a property LinksMap which holds another object.

Related

How to get a list via POST in Restangular?

Consider a REST URL like /api/users/findByCriteria which receives POSTed JSON that contains details of the criteria, and outputs a list of Users.
How would one call this with Restangular so that its results are similar to Restangulars getList()?
Restangular.all('users').post("findByCriteria", crit)... might work, but I don't know how to have Restangular recognize that the result will be a list of Users
Restangular.all('users').getListFromPOST("findByCriteria", crit)... would be nice to be able to do, but it doesn't exist.
Doing a GET instead of a POST isn't an option, because the criteria is complex.
Well,
I experience same problem and I workaround it with plain function, which return a plain array of objects. but it will remove all Restangular helper functions. So, you cant use it.
Code snippet:
Restangular.one('client').post('list',JSON.stringify({
offset: offset,
length: length
})).then(
function(data) {
$scope.clients = data.plain();
},
function(data) {
//error handling
}
);
You can get a POST to return a properly restangularized collection by setting a custom handler for OnElemRestangularized in a config block. This handler is called after the object has been Restangularized. isCollection is passed in to show if the obect was treated as a collection or single element. In the code below, if the object is an array, but was not treated as collection, it is restangularized again, as a collection. This adds all the restangular handlers to each element in the array.
let onElemR = (changedElem, isCollection, route, Restangular: restangular.IService) => {
if (Array.isArray(changedElem) && !isCollection ) {
return Restangular.restangularizeCollection(null, changedElem, changedElem.route);
}
return changedElem;
};
RestangularProvider.setOnElemRestangularized(onElemR);

calling JSON webservice & using html

I've been using XML a lot lately but now I'm practicing with some JSON.
What I am trying to do is make a button and text box - so the user can type in a zip code and it will get the info for that zip code...
Using JSON from geonames.org
It's frustrating me trying to figure this out, I've found it easy when I was making my own files with XML but now I am trying to use an actual website and JSON.
Please show me how to do this! Would appreciate it! Thanks.
First of all HTML cannot process a json response from a server. You can send a get or post in json format to a server and get a json response back but you need something other than HTML to process that JSON message. Browsers can format and display XML but not JSON (they just display it as a string). The easiest way to do that in a browser is use JavaScript. For this I would recommend using the jquery library.
http://jquery.com
Here's an example of some jquery I used recently to process a returned JSON string.
$(document).ready(function() {
$(".img a").on("click", function(event) {
event.preventDefault();
var item;
if ((item= $(this).attr( 'href' ))=="saved") return false;
$(this).html("<div style='line-height:4em '>Saved</div>");
$(this).attr("href","saved");
var action ="add";
jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) {
var result=data.result;
if (result=="saved") {
self.html("<div>Saved</div>");
self.attr("href","saved");
}
}, "json")
.error(function() {
alert("error: unable to contact web service");
});
});
});
The returned JSON string from this request is { result: saved }. So as you can see you access the associated array as part of the data object. In my case data.result provided me with the value of result from the json string.
Note my example is for using an anchor tag to pass a value to send in the webservice call. In your case you will need to use a form.
If you're using jeoquery then just look at the html source of UI sample. It's showing the same autocomplete box that you might be trying to implement no custom code to write to parse returned JSON. Below code should work for you:
<input class="input-large" id="city" type="text"/>
$("#city").jeoCityAutoComplete();

JSON to usable array javascript

I'm trying to convert my JSON code to a usable array in javascript/jquery.
I have the following JSON code arriving via ajax:
[{"id":"9","firstname":"Greg","surname":"Bril","position":"0","busy":"0","disabled":"0"},{"id":"14","firstname":"Nai","surname":"Brooks","position":"1","busy":"0","disabled":"0"},{"id":"17","firstname":"Margaret","surname":"Grey","position":"1","busy":"0","disabled":"0"},{"id":"1","firstname":"Cameron","surname":"Grover","position":"0","busy":"0","disabled":"0"},{"id":"2","firstname":"Sarah","surname":"Grover","position":"0","busy":"0","disabled":"0"},{"id":"3","firstname":"Margaret","surname":"Hynes","position":"0","busy":"0","disabled":"0"},{"id":"4","firstname":"Stephen","surname":"Hynes","position":"0","busy":"0","disabled":"0"},{"id":"11","firstname":"Ben","surname":"Mills","position":"1","busy":"0","disabled":"0"},{"id":"15","firstname":"Elizabeth","surname":"Mills","position":"1","busy":"0","disabled":"0"},{"id":"10","firstname":"Grant","surname":"Mills","position":"0","busy":"0","disabled":"0"},{"id":"16","firstname":"John","surname":"Mills","position":"1","busy":"0","disabled":"0"},{"id":"13","firstname":"Lucinda","surname":"Ower","position":"1","busy":"0","disabled":"0"},{"id":"12","firstname":"Karina","surname":"Scott","position":"1","busy":"0","disabled":"0"}]
It is created and intepreted using:
$.getJSON( "tc_search1.php", {
leave: $("input#leave").val(),
end: $("input#end").val(),
override: $("#tc_override").is(":checked"),
tc_id: $("#tc_id").val()
}, function(data) {
//i cant get this part to work
});
I can't seem to manage to get the function on success to work. I tried the $.each method on jquery documentation website, but I can't get it right. Can anyone help?
The getJSON method will automatically parse the JSON string into a Javascript object.
The data parameter in your success callback function will be an array of objects. For example, the expression data[0].firstname will return "Greg".

Get custom JQGrid JSON data in gridComplete method

Here is a typical JQGrid JSON response:
{
"page":1,
"records":537,
"rows":[..],
"rowCount":10,
"total":54
}
Along with this, I want to send additional custom data. For example, I'd like to send the database time of the last search so that I can lazy-reload my grid whenever changes have occurred since then. Here is how I would like to send that data:
{
//Custom name-value pairs:
"nameValues":{"lastSearchTime":"2011/09/01:14:14:56"},
//Normal JSON data:
"page":1,
"records":537,
"rows":[..],
"rowCount":10,
"total":54
}
The problem is that JQGrid swallows up the JSON response rather than forwarding it to the gridComplete method. In other words, params is undefined in the following function:
function myGridComplete (params){
//params is undefined!
var JSONResponse = ?;//I need your help here!!!
globalGridVariables.lastSearchTime = JSONResponse.nameValues.lastSearchTime;
//Rest of grid complete method
..
}
Please let me know if there is a way to get access to the JSON response object in the gridComplete method, or if there is another supported way to add custom data to a JSON response.
Thanks much!
Note: I don't want to send this as a hidden column, because that would be inefficient.
You can use loadComplete instead of gridComplete. The loadComplete event has one parameter (for example data) which represent the full data from the server response inclusive all of your extensions.
Alternative you can rename the nameValues to userdata and use $('#list').jqGrid('getGridParam', 'userData') to get the value. See here for more information.
Moreover you can consider to use more HTTP caching (see here and here) for the aims which you described in your question.
You can use beforeProcessing that has the deserialized response and gets active before gridComplete and loadComplete.
For example:
beforeProcessing: function (data, status, xhr) {
myArray = data.rows;
}
And just to make it more clearer from the documentation:
Below is the execution order of the events when a ajax request is made
beforeRequest
loadBeforeSend
serializeGridData
loadError
beforeProcessing
gridComplete
loadComplete

asp.net mvc 3 ViewModel collection property to json not working

Good evening everyone. I am currently using MVC 3 and I have a viewmodel that contains a property that is a List. I am currently using json2's JSON.stringify method to pass my viewmodel to my action method. While debugging I am noticing that all the simple properties are coming thru but the collection property is empty even though I know for sure that there is at least one object in the collection. I wanted to know if there is anyone that is running into the same issue. Below is the code that I am using to post to the action method:
$.post("/ReservationWizard/AddVehicleToReservation/",
JSON.stringify('#ViewData["modelAsJSON"]'),
function (data) {
if (data != null) {
$("#vehicle-selection-container").html(data);
$(".reservation-wizard-step").fadeIn();
}
});
The object #ViewData["modelAsJSON"] contains the following json and is passed to my action method
{"NumberOfVehicles":1,"VehiclesToService":[{"VehicleMakeId":0,"VehicleModelId":0}]}
As you can see the property "VehiclesToService" has one object but when it gets to my action method it is not translated to the corresponding object in the collection, but rather the collection is empty.
If anyone has any insight into this issue it would be greatly appreciated.
Thanks in advance.
UPDATE
OK after making the recommended changes and making the call to new JavaScriptSerializer().Serialize(#Model) this is the string that ultimately gets sent to my action method through the post
'{"NumberOfVehicles":1,"VehiclesToService":[{"VehicleMakeId":0,"VehicleModelId":0}]}'
I can debug and see the object that gets sent to my action method, but again the collection property is empty and I know that for sure there is at least one object in the collection.
The AddVehicleToReservation action method is declared as follows:
public ActionResult AddVehicleToReservation(VehicleSelection selections)
{
...
return PartialView("viewName", model);
}
Here's the problem:
JSON.stringify('#ViewData["modelAsJSON"]')
JSON.stringify is a client side function and you are passing as argument a list that's stored in the ViewData so I suppose that it ends up calling the .ToString() and you have
JSON.stringify('System.Collections.Generic.List<Foo>')
in your final HTML which obviously doesn't make much sense. Also don't forget that in order to pass parameters to the server using the $.post function the second parameter needs to be a javascript object which is not what JSON.stringify does (it generates a string). So you need to end up with HTML like this:
$.post(
'ReservationWizard/AddVehicleToReservation',
[ { id: 1, title: 'title 1' }, { id: 2, title: 'title 2' } ],
function (data) {
if (data != null) {
$('#vehicle-selection-container').html(data);
$('.reservation-wizard-step').fadeIn();
}
}
);
So to make this work you will first need to serialize this ViewData into JSON. You could use the JavaScriptSerializer class for this:
#{
var myList = new JavaScriptSerializer().Serialize(ViewData["modelAsJSON"]);
}
$.post(
'#Url.Action("AddVehicleToReservation", "ReservationWizard")',
// Don't use JSON.stringify: that makes JSON request and without
// proper content type header your sever won't be able to bind it
#myList,
function (data) {
if (data != null) {
$('#vehicle-selection-container').html(data);
$('.reservation-wizard-step').fadeIn();
}
}
);
And please don't use this ViewData. Make your views strongly typed and use view models.