I have this json object :
[
{
"company_name": "Spix Clothing Co."
},
{
"company_name": "spixel"
},
{
"company_name": "WebNiJose Co."
}
]
As you can see, its an object without a name, and has 3 objects within it.
I wonder if how am I suppose to handle this. I want each one to be in appended in <ul></ul>.
By the way, that is a response from an ajax call, like this:
success : function(output) {
console.log(output);
}
And the php file fire that like this:
echo json_encode($result);
How do you think is the best way to handle that?
The response that you're receiving is actually an array so you would handle this situation as follows:
Parse the string into an object that you can use in javascript:
var companyObject = JSON.parse(output);
Loop through the array and pull out the object attributes and create a new <li> element to contain for example the company name. JQuery provides an automatic index for us to use if you wish. (Assuming your markup already has an <ul> element with an id of "container".)
var $container = $('#container'); // where to append the <li>
$.each(companyObject,function(i,company){
var $newElement = $('<li/>'); // create a new <li> element
$newElement.html(company.company_name);
$container.append($newElement); // attach the new <li> element
});
Here is a full example: http://jsfiddle.net/mNzm9/2/
Related
I have a form page where the user selects a filter and a table on the bottom of the page updates. Each line in the table has a hyperlink in column one that associates a line item to an item in the database. I am not using GORM.
I need to be able to send the current filters to the controller via AJAX (functioning). Then I need to render a partial template (to a div) that loads the data created by a query based on the client's request parameters.
GSP:
....
<button onClick="generate_table()" class="pure-button">Generate Table</button>
...
<div id="selection_table">This should load with data</div>
...
JS:
//Link for AJAX
var url = "${g.createLink(action:'generate_table', controller: "statusReports")}";
//The actual call
$.getJSON(url, {
period: JSON.stringify($("#period").val()),
...
...
}, function(data) {
$('#selection_table').empty();
}).done(function(data) {
//I need to load the template at this point?
})
Controller:
def generate_table(){
def table_data = statusReportsService.generate_titles(params)
// Table data is already a map
// What do I need to render here? The template is named _selectionTable.gsp and should use table_data to generate html.
}
Partial:
I still haven't written the code for this yet. For now it is just some random text to see if I can even load the template when I press the button
In your controller:
render(template: 'selectionTable', model: table_data)
In your GSP/HTML you need to use $.get and use the following:
$('#selection_table').html(data)
That should do the trick!
For a list of items I want to show details after item click. Details will be loaded with ajax request.
I have something similar to this: http://jsfiddle.net/asmKj/
How to modify this to work with details loaded dynamically?
For sure I have to prepare function in my controller like this:
$scope.getDetails = function (name) {
return $scope.details = myService.getDetails(name).then(function (details) {
return $scope.details = details;
});
}
But how to bind this data to details div?
I would rather change with something like this:
HTML
<ul class="procedures" ng-app ng-controller="sample">
<li ng-repeat="procedure in procedures">
<h4>{{procedure.definition}}</h4>
<div class="procedure-details" ng-show="procedures.isVisible">
<p>Number of patient discharges: {{procedure.discharged}}</p>
</div>
</li>
</ul>
JS
$scope.procedures = [
{
definition: 'Procedure 1',
discharged: 23
},
{
definition: 'Procedure 2',
discharged: 2
},
{
definition: 'Procedure 3',
discharged: 356
}
];
$scope.getDetails = function ($index) {
$http.get('your-url').success(
// use the data retrieved
procedures[$index].isVisible = !procedures[$index].isVisible;
);
}
There are basically two options.
Put everything in your procedure objects as separate properties (when the details are loaded) -- then you can just use procedure.showDetails in ng-repeat.
Use $index to get index from your procedures -- then you can use it to access any arbitrary collection from your scope in ng-repeat.
(may update my answer, when you provide more info about structure of your data; and if still needed)
I have a small extract from my Ember app here. My page contains a number of views each containing different data each with their own controllers.
I want a search field (in index view) to go in one view which should "talk" to the stationList controller to update the content of the stationList view. This doesn't work. I get an error: TypeError: this.get(...).search is not a function
The logging outputs the name of the contoller I've asked it to use: App.StationListController
I added a second search form inside on the StationList View. This one works just fine. The logging this time outputs a dump of the StationListController object. So I am guessing that the other search form, despite my code (in SearchFormView): controllerBinding : 'App.StationListController', is not correctly setting the controller.
So I guess my question is why not?
How can I route the change on the form field in the one view to call a funciton on another view's controller?
Here's my code:
<script type="text/x-handlebars" data-template-name="application">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<div id="searchForm">search form view search:
{{#view App.SearchFormView}}
{{view App.StationSearchField}}
{{/view}}
</div>
<div id="stationList">{{render stationList}}</div>
</script>
<script type="text/x-handlebars" data-template-name="stationList">
station list view search: {{view App.StationSearchField}}
<ul>
<li>List</li>
<li>will</li>
<li>go</li>
<li>here</li>
</ul>
{{searchTerm}}
</script>
And
App = Ember.Application.create({})
App.SearchFormView = Ember.View.extend({
init : function()
{
console.log("SearchFormView init", this.get('controller'))
}
})
App.StationSearchField = Ember.TextField.extend({
keyUp: function(event) {
var searchTerm = this.value
console.log("value",searchTerm,this.get('controller'))
this.get('controller').search(searchTerm)
}
})
App.StationListController = Ember.ArrayController.extend({
content : [],
searchTerm : null,
search : function(term)
{
this.set("searchTerm",term)
console.log("searching",term)
}
});
Fiddle: http://jsfiddle.net/ianbale/8QbrK/14/
I think the controllerBinding stuff is from the older version, I don't think that works anymore.
You can use controllerFor on get('controller') in the StationSearchField.
this.get('controller').controllerFor('station_list').search(searchTerm)
But controllerFor is deprecated and may be removed. Depending on your application structure you use needs on the controller.
Another way which I am using, is to send a custom event from the View, which the Route then sends to the corresponding controller.
App.IndexRoute = Ember.Route.extend({
events: {
search: function(term) {
controller = this.controllerFor('station_list')
controller.search(term);
}
}
});
and dispatch a search event from view like so.
this.get('controller').send('search', searchTerm);
The advantage of this method is you dispatch the same event from multiple places and it would get handled in the same way.
Here's the updated jsfiddle.
I have a JSP page which shows items included in an Array (Just a very simple list).
In the background the Array might change i.e. adds a new Item or remove one.
How can I auto refresh the page when the Array changes?
There are 2 ways that are most popular to perform such operation
pool a method that would send 1 or 0 to see if you refresh the page or not
keep asking for that data array and populate it through javascript
Option 1
create a .jsp page and call it, for example, updateList.jsp
add a single method that will check if there is more data to be filled and output 1 or 0 like: out.println(1)
in your page, and using jQuery to simplify things
$.get("updateList.jsp", function(data) {
if(data !== null && data.length > 0 && data === 1) {
// refresh this page
document.location = document.location.href;
}
});
Option 2
create a .jsp page and call it, for example, data.jsp
add a single method that will output a JSON string containing all data you need to populate the list
in your page, and using jQuery and JsRender to simplify things
$.get("updateList.jsp", function(data) {
if(data !== null && data.length > 0) {
$("#my-list").html(
$("#my-template").render(data);
);
}
});
and in your HTML you will have:
<ul id="my-list"></ul>
<script id="my-template" type="text/x-jsrender">
{{for items}}
<li>{{:name}}</li>
{{/for}}
</script>
assuming your JSON would be something like:
item: [
{ name: "Name A" },
{ name: "Name B" },
{ name: "Name C" },
]
Once the JSP has been executed, the HTML code that it has generated has been sent to the browser, and there is no connection between the browser and the JSP anymore. If you want to refresh some part of the page, you need to poll the server using AJAX, or use WebSockets to maintain a connection between the page and the server.
To refresh page silently use AJAX. Below are some examples
Example 1
Example 2
Google Search
Using node.js and express (2.5.9) with express-form.
How should I repopulate form fields with the submitted values?
I have a get and a post route. If there are validation errors when the form is posted, I redirect the user back to the get, the problem is that the repopulated locals don't show up (I do have autoLocals: true, so I assume it's because I am redirecting and res is reset.)
So how do you guys repopulate and what's your application flow, do you res.send instead of res.redirect and set up the whole thing again? That seems repetitive.
Here's an example of my post route:
app.post(
'/projects/:id'
, form(field("title").required("title", "Title is required)
, function (req, res){
if (!req.form.isValid){
res.redirect('/project/'+req.params.id+'/edit');
}
else{
// save to db
}
});
I am working with expressjs4.0 to repopulate the forms fields after validation you do:
router.route('/posts/new')
.get(function(req, res) {
res.render('posts/new', new Post({}));
});
The second argument in res.render below will set some variables in the view.
res.render('posts/new', new Post({}));
In my view I then set my form fields as follows:
...
<input type="text" name="title" value="<%- post.title %>">
<textarea name="article"><%- post.article %></textarea>
...
When you submit this form, it should be caught by your router like so:
router.route('/posts')
.post(function(req, res) {
var post = new Post(req.body)
post.save(function(err) {
if (err) {
res.locals.errors = err.errors;
res.locals.post = post;
return res.render('posts/new');
}
return res.redirect('/posts');
});
...
})
This line of code, resets the form fields in your view
res.locals.post = post;
I hope someone finds this useful ;)
Not sure if it's best practice, but when I have validation failure, I don't redirect I just re-render the view (often by passing control to the 'get' callback). Somethign like this:
function loadProject(req,res, id){ /* fetch or create logic, storing as req.model or req.project */}
function editProject(req,res){ /* render logic */ }
function saveProject(req,res){
if(!req.form.isValid){
editProject(req,res);
}else{
saveToDb(req.project);
res.redirect('/project'+req.project.id+'/edit');
}
}
app.param('id', loadProject);
app.get('/projects/:id/edit', editProject);
app.post('/projects/:id', saveProject);
I had to work on similar problem recently and used two node modules: validator and flashify.
In the form view I configured my form fields as follows:
div.control-group
label.control-label Description
div.controls
textarea(name='eventForm[desc]', id='desc', rows='3').input-xxlarge= eventForm.desc
div.control-group
label.control-label Tag
div.controls
select(id='tag', name='eventForm[tag]')
tags = ['Medjugorje', 'Kibeho', 'Lourdes', 'Fatima']
for tag in tags
option(selected=eventForm.tag == tag)= tag
Notice the naming convention of the form fields. Then in my config file I set one global variable, which is really just a placeholder for when the form first loads:
//locals
app.locals.eventForm = []; // placeholder for event form repopulation
The validation logic is in my router file and looks like this:
app.post('/posts', function(req, res){
var formData = req.body.eventForm;
var Post = models.events;
var post = new Post();
post.text = formData.desc;
post.tag = formData.tag;
// run validations before saving
var v = new Validator();
var isPostValid = true;
// custom error catcher for validator, which uses flashify
v.error = function(msg) {
res.flash('error', msg);
isPostValid = false;
}
v.check(post.text, "Description field cannot be empty").notEmpty();
v.check(post.tag, "Tag field cannot be empty").notEmpty();
Then I check to see there are errors, and if so, pass the form data back to the view:
// reject it
res.render('Event.jade', {page: req.session.page, eventForm: formData});
Notice this evenForm data gets passed back to the view, which repopulates the default values.
The final step is to include the flashify component in your form view.
div(style='margin-top: 60px').container-fluid
include flashify
The code for the flashify view looks like this:
if (flash.error != undefined)
div.container
div.alert.alert-error
b Oops!
button(type='button', data-dismiss='alert').close ×
ul
each error in flash.error
li= error
if (flash.success != undefined)
div.container
div.alert.alert-success
b Success!
button(type='button', data-dismiss='alert').close ×
ul
each success in flash.success
li= success