I have a struts 2 action class with a method which returns json data.
I have 8 tabs on my jsp. When a user clicks on a tab, I'd like to make an ajax call to this method. I would like the returned json data to be parsed and decorated with html that can be rendered in this tab.
I'm using jquery tabs to make tabs.
How can I capture the returned json data ? Can I subscribe to some event that jquery publishes ?
How can I process the returned json data ? For e.g.; json data:
{ City : {name="New York", alias="NY", imgPath="filePath/img1.jgp"} }
I would like to extract the name and bold it.
Use the imgPath to define img tag, etc
$(document).ready(function () {
var data = { "City": [{ "name": "New York1", "alias": "NY1", "imgPath": "filePath/img1.jgp" }, { "name": "New York2", "alias": "NY2", "imgPath": "filePath/img2.jgp" }, { "name": "New York3", "alias": "NY3", "imgPath": "filePath/img3.jgp" }, { "name": "New York4", "alias": "NY4", "imgPath": "filePath/img4.jgp"}] };
if (data.City.length > 0) {
$('body').prepend('<div id="tabs1"><ul></ul></div>');
$.each(data.City, function (i, entity) {
$('#tabs1 ul').append($('<li>' + entity.name + '</li>'));
$('#tabs1').append('<div id="tabs1-' + (i + 1) + '"><p>Image Path:' + entity.imgPath + '</p></div>');
});
$("#tabs1").tabs();
}
});
for live demo see this link: http://jsfiddle.net/nanoquantumtech/ffbx5/
You can capture the returned Json data by passing the data argument to the ajax calls success callback method which will be executed on success. http://api.jquery.com/jQuery.ajax/
You can use jQuery parse.json method and pass the json string to it. http://api.jquery.com/jQuery.parseJSON/
One more thing that your example json string is not looks like valid one. You can check your json is valid or not from this link http://jsonlint.com/ by simply pasting your json data or by pasting the url.
Related
I am developing a polymer app and I want to make a call to the RestApi.
this is the how the request body is
{
"languageId": Presently English is the only supported language. Always 1,
"productCode":"Medicus",
"timeZoneName":"Time zone name of device. For e.g. Asia/Calcutta",
"timeZoneOffset": Time zone offset from UTC in milliseconds. For e.g. IST = 19800000,
"user":{
"firstName":"First name of the user",
"lastName":"Last name of the user",
"middleName":"Middle name of the user",
"password":"Password provided by the user",
"userTypeId":2 = Doctor, 3 = User,
"fields":[
{
"Id":1,
"values":["Mobile number provided by the user”]
}
]
}
}
i am not getting the proper idea of how i should specify these parameters in the params='{}' of iron-ajax element.
Put something like this in your template (I am assuming POST to your rest API, since you said body in your question. If its GET replace body= with params=
<iron-ajax
id="fetchday"
url="/api/fetchday"
handle-as="json"
content-type="application/json"
method="POST"
body="[[params]]"
last-response="{{results}}"
on-response="_gotData"
on-error="_error"></iron-ajax>
And in your polymer element properties
Polymer({
is: 'my-element'
properties: {
params: {
type: Object
}
},
_someFunction: function() {
this.params = //ASSIGN YOUR JSON OBJECT TO PARAMS HERE
this.$.fetchday.generateRequest();
},
_gotData: function(e) {
//response data is in both this.results and e.detail.response
},
_error: function() {
}
});
I'm building a datatable using ajax data which is provides customer data after authentication. Is there a way to pickup the username during authentication and display it on the page to clearly indicate that the table contains the customer's personalised data?
Can I have the username stored in the ajax data file as the "dataSrc".
{
"username": [
[
"item1",
"item2",
"item3"
]
]
}
Then it could be picked up as a variable and then displayed on the page.
var oTable = $('#example').DataTable({
"ajax": {
"url": "data/customerdata.txt",
"type": "POST",
"dataSrc": function(...
},
Thank you in advance for your help!
Something like this should work:
"dataSrc": function (json){
console.log(json.username); // Should output your array e.g. ["item1", "item2","item3"]
$.each(json.username, function(k, v){
console.log(k, v) // Should output each element of your array e.g 0 and item1 then 1 and item2 and then finally 2 and item3
// You can display what you want on the page from this data.
});
return json.data; // returns the data to the table so it can be drawn.
}
Hope that that helps.
I have the following code base to share with you guys to list the pages that fetch using the query builder via AJAX call. We have to pass the URL and the parameters to fetch the child pages from the URL that we provide.
I have put some console.log to track the values of each states.
replace the with your project.
<featurearticles
jcr:primaryType="cq:Widget"
fieldLabel="Article Pages"
itemId="selectauthorId"
name="./authorselect"
type="select"
xtype="selection">
<options jcr:primaryType="cq:WidgetCollection"/>
<listeners
jcr:primaryType="nt:unstructured"
loadcontent="function(box,value) {
CQ.Ext.Ajax.request({
url: '/bin/querybuilder.json',
success: function(response, opts) {
console.log('Response from the ajax');
var resTexts = $.parseJSON(response.responseText);
var selectopts = [];
console.log(resTexts);
$.each(resTexts.hits, function(key, page) {
console.log(page);
selectopts.push({value: page['path'], text:page['name']});
});
console.log(selectopts);
box.setOptions(selectopts);
},
params: {
'type' :'cq:Page',
'group.1_path' : '/content/<PROJECT_NAME>/Feature_Articles'
}
});
}"
selectionchanged="function(box,value) {
var panel = this.findParentByType('panel');
var articleTitle = panel.getComponent('articleTitleId');
CQ.Ext.Ajax.request({
url: value + '/_jcr_content/par/featurearticleintro.json',
success: function(response, opts) {
console.log('success now');
var resTexts = $.parseJSON(response.responseText);
console.log(resTexts);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
}"/>
</featurearticles>
If you have any better idea than this, I would like to know about that.
Cheers,
Another alternative is to use the "options" attribute of the selection xtype to fetch the dropdown list options from an AJAX call via a servlet or sling selector. The widgets api (http://dev.day.com/docs/en/cq/5-6/widgets-api/index.html - search for "selection") says this for the options attribute:
If options is a string it is assumed to be an URL pointing to a JSON
resource that returns the options (same structure as above applies).
This should be either an absolute URL or it can use the path of the
content resource being edited using a placeholder
(Selection.PATH_PLACEHOLDER = "$PATH"), for example:
$PATH.options.json.
So it may be a cleaner approach to build a servlet that will respond with JSON to an AJAX request, then put this servlet as the "options" attribute. For example, the attribute might be something like options="/libs/myServlet" or something like options="$PATH.options.json". That may make the dialog cleaner (no listener required), and it uses built-in CQ capability to fetch options via AJAX.
We can use the dynamic dropdown as below:
<item
jcr:primaryType="cq:Widget"
fieldLabel="Item"
name="./item"
optionsRoot="root"
options="/bin/service/item.json"
type="select"
xtype="selection"/>
options: the url will return the json format for the selection xtype
optionsRoot: the name of the root item of the json
optionsTextField: the name of text field (default value: "text")
optionsValueField: the name of the value field (default value: "value")
Example of json: {"root":[{"text":"Item 1", "value":"Value 1"},{"text":"Item 2", "value":"Value 2"},{"text":"Item 3", "value":"Value 3"}]}
Selection xtype
I'm trying to pre-populate a form made with angularJS with previously inserted data using JSON
Everything is working fine except for the select option items that are not populated.
A JSON example I'm using is:
{
"date": "2014-09-14",
"enumerator": "a",
"monthreport": {
"value": "March"
},
"weekreport": {
"value": "2nd week"
},
"Maize": 23,
"Wheat": 41,
"Sorghum": 71,
"q14": "Yes"
}
monthreport and weekreport are select option and they are not filled in when the form is loaded.
q14 is a radiobutton, and it works fine as all the other input text field, both text and numeric.
The JSON is the one produced exactly by angularJS, when I fill in the data in the form and then save it.
the select element is specified in this way in the HTML:
<select ng-model="currForm.weekreport" ng-options="o.value for o in options16" name="r_weekreport" required ></select>
and the options are set in the controller:
...
$scope.options16= [{value:"1st week"},{value:"2nd week"},{value:"3rd week"},{value:"4th week"},{value:"5th week"}];
...
To load JSON I use the usual function inside the app.controller:
...
$http({
method: 'GET',
url: 'http://samplesite.com/formJSON.txt'
}).success(function(data, status) {
console.log('works!!! ' + data);
$scope.currForm = data; }).error(function(data, status) {
// Some error occurred
console.log(status);
})
...
it seems everything right... where I'm wrong??
You can try:
<select ng-model="currForm.weekreport.value" ng-options="o.value as o.value for o in options16" name="r_weekreport" required ></select>
This happens because angular compares objects in your example and they are not equal. You need to compare primitives.
So I'm trying to use AJAX to load some data. I can get the data to load but it's stuck in json. How do I make it so it's cleaner & more human readable?
//jquery
$.get("/get_artwork", function(data) {
var obj = jQuery.parseJSON(data)
$('.result').append("<br/> " + data + " ");
});
#Views.py
def get_artwork(request):
if request.is_ajax():
artwork = Artwork.objects.all()[1:]
if request.method == 'GET':
data = serializers.serialize("json", artwork, fields=('name','updated'), indent=2, use_natural_keys=True)
return HttpResponse(data,mimetype='application/javascript')
elif request.method == 'POST':
message = "This is an XHR POST request"
# Here we can access the POST data
print request.POST
else:
message = "Hello"
return HttpResponse(message)
and this is what renders:
[ { "pk": 3, "model": "artworks.artwork", "fields": { "updated": "2013-01-20T06:46:24Z" } }, { "pk": 2, "model": "artworks.artwork", "fields": { "updated": "2013-01-17T23:44:26Z" } }, { "pk": 1, "model": "artworks.artwork", "fields": { "updated": "2013-01-17T23:43:22Z" } } ]
How would I make this more human-readable? Thanks!
Based on the comments you've left.. it seems your issue is downstream in the client (e.g. web browser). It is not clear what you mean by stuck in JSON. If you are using JavaScript to parse the JSON, you will need to use JSON.parse() to turn it into a native JavaScript object. If you are using jQuery and the $.ajax() method, you will need to set the mimetype to application/json for it to automatically parse it as JSON.
UPDATE
If you want to control how the JSON data is rendered in the browser, I suggest you parse the JSON response into a native JavaScript object and then iterate over objects and fields you want to render in the page. As an example, using jQuery:
$.ajax({
url: '/some-url/',
dataType: 'json',
success: function(resp) {
var i, k, li, obj, fields;
for (i = 0; i < resp.length; i++) {
obj = resp[i];
// render obj pk or model name here... now iterate over fields
fields = obj.fields;
for (k of obj.fields) {
li = $('<li>').text(k + ': ' + obj.fields[k]);
// append the li to some element..
}
}
}
});