passing python data to javascript in web2py - javascript

Here is my problem. I have the following function
def index():
rows=db(db.mylist).select()
return dict(rows=rows)
so whenever I reload the the front view index I want to retrieve rows from the database and display the data to the user in a list
{{for(r in rows)}}
li.innerhtml={{=rows.task}}
{{pass}}
Obviously, this is not the right way to do it. I think I have to use json and XML.
This is the table I am using
db.define_table(
'mylist',
Field('task', 'string')
)
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-heading center " style="color: black; font-style: inherit">
<form>
Task:
<input name="name" id="task" />
<button type="button" class="btn btn-success btn-sm" onclick=add(),ajax('{{=URL('default','insert_task')}}',['name']) >add</button>
</form>
</div>
<div class="panel-body center">
<ul id="list" class="list-group"> </ul>
</div>
</div>
</div>
</div>
var ul = document.getElementById("list");
var lastId=0;
function add()
{
if(!isBlank(document.getElementById("task").value)) {
var iCon = document.createElement('div'); //create a div container
var dbtMenu=document.createElement('div');
var li = document.createElement("il"); //create a list-element
var closeSpan = document.createElement("span"); //create a span for badge attribute
var ClickListState=0;
dbtMenu.setAttribute("class","container");
//dbtMenu.appendChild(dropDownList);
li.setAttribute('id',lastId); // set an attribute for id
iCon.className = "glyphicon glyphicon-remove"; // image for remove button
closeSpan.setAttribute("class", "badge"); //create a new attribute for span
closeSpan.appendChild(iCon); // put it in the span set
iCon.addEventListener("click",function(){var element=document.getElementById(li.getAttribute('id'));
element.parentNode.removeChild(element);}); //functionlity
li.innerHTML = document.getElementById('task').value;
var value=document.getElementById('task').value;
var pass= document.getElementById('task').value;
li.setAttribute("class", "list-group-item hover-yellow");
li.addEventListener('click',function() {if(ClickListState==0){li.style.backgroundColor="red"; ClickListState++;}
else {li.style.backgroundColor="white"; ClickListState--; }});
li.appendChild(closeSpan);
lastId++;
ul.appendChild(li);
}
}
function update()
{
{{for r in rows:}}
var iCon = document.createElement('div'); //create a div container
var dbtMenu = document.createElement('div');
var li = document.createElement("il"); //create a list-element
var closeSpan = document.createElement("span"); //create a span for badge attribute
var ClickListState = 0;
dbtMenu.setAttribute("class", "container");
//dbtMenu.appendChild(dropDownList);
li.setAttribute('id', lastId); // set an attribute for id
iCon.className = "glyphicon glyphicon-remove"; // image for remove button
closeSpan.setAttribute("class", "badge"); //create a new attribute for span
closeSpan.appendChild(iCon); // put it in the span set
iCon.addEventListener("click", function () {
var element = document.getElementById(li.getAttribute('id'));
element.parentNode.removeChild(element);
});
// var t ={#{=XML(response.json(r.task))}}
li.innerHTML = "t";
var value = document.getElementById('task').value;
var pass = document.getElementById('task').value;
li.setAttribute("class", "list-group-item hover-yellow");
li.addEventListener('click', function () {
if (ClickListState == 0) {
li.style.backgroundColor = "red";
ClickListState++;
}
else {
li.style.backgroundColor = "white";
ClickListState--;
}
});
li.appendChild(closeSpan);
lastId++;
ul.appendChild(li);
{{pass}}
}
update();

Read the basic syntax for template language in web2py here
You want this:
<ul>
{{for row in rows:}}
<li>{{=row}}</li>
{{pass}}
</ul>
Other solution can be, build the complete list in controller function using html helpers and pass it to view
def index():
rows = db(db.mylist).select()
my_list = [row.task for row in rows]
task_list = UL(*my_list)
return dict(task_list=task_list)
And in the view just do:
{{=XML(task_list)}}
XML is an object used to encapsulate text that should not be
escaped.
I will suggest you to go through these 2 examples: Image blog and Simple wiki
EDIT:
From your edit, I think you want to add new task using form and wanted to add the list without refreshing the page.
Read Ajax form submission, also related ajax example is given in simple wiki app
<!-- Views/index.html-->
{{extend 'layout.html'}}
<form id="task_form">
Task:
<input name="name" id="task" />
<input type="submit" class="btn btn-success btn-sm" value="Add" />
</form>
<div id="target"> {{=XML(task_list)}}</div>
<script>
jQuery('#task_form').submit(function() {
ajax('{{=URL("default", "insert_task")}}',
['name'], 'target');
return false;
});
</script>
--
# Controller
def index():
rows = db(db.mylist).select()
my_list = [row.task for row in rows]
task_list = UL(*my_list)
return dict(task_list=task_list)
def insert_task():
"""an ajax callback that returns a <ul>"""
task_name = request.vars.name
db.mylist.insert(task=task_name)
rows = db(db.mylist).select()
my_list = [row.task for row in rows]
task_list = UL(*my_list)
return task_list

I came up with this to convert a python list of strings to a javascript array of strings:
{{def print_js_array(left_side, pylist):
wrap_quotes = map(lambda a: "'{}'".format(a), pylist)
comma_separated = "" if not pylist else reduce(lambda a,b: "{}, {}".format(a,b), wrap_quotes)
return "{} = [{}];".format(left_side, comma_separated)
}}
{{=SCRIPT(
""
+ print_js_array("var un_pythoned", status_filter_options))
}}
Which given a python list ['', 'Not Started', 'Running', 'Finished', 'Failed'] results in (html):
<script><!--
var un_pythoned = ['', 'Not Started', 'Running', 'Finished', 'Failed'];
//--></script>
Making the array available to subsequent scripts. You could probably write something similar to print a dictionary as json.

Related

Deleting class from an element

I'm making a task board project.
Must say I'm using only HTML, CSS, JS, and nothing else right now.
I'm making a fade-in effect to the newly added note (ul element), and I would like to delete the fade-in class from the previously added note.
this is a chunk of my code that displays the note inside the div.
function displayAllTasks(allTasks){
taskNotesDiv.innerHTML = "";
for(const task of allTasks){
const index = allTasks.indexOf(task);
const note = `
<div class"noteDiv">
<ul class="fadeInNote">
<button type="button" onclick="deleteTask(${index})">
<i class="fa-solid fa-trash deleteButton"></i>
</button>
<li>Task: ${task.task}</li>
<li>Description: ${task.textArea}</li>
<li>Date: ${task.date}</li>
<li>Time: ${task.time}</li>
</ul>
</div>
`
taskNotesDiv.innerHTML += note;
}
}
I tried already another function to delete it but with no success.
any help would be appreciated!
There can be multiple approaches, but my approach is to create element using document.createElement . The modified JS will become:
function displayAllTasks(allTasks) {
last_ul = null; // store the last ul element added
taskNotesDiv.innerHTML = "";
for (const task of allTasks) {
const index = allTasks.indexOf(task);
let noteDiv = document.createElement('div');
noteDiv.classList.add('noteDiv');
note_ul = document.createElement('ul');
note_ul.classList.add('fadeInNote');
note_ul.innerHTML = `
<button type="button" onclick="deleteTask(${index})">
<i class="fa-solid fa-trash deleteButton"></i>
</button>
<li>Task: ${task.task}</li>
<li>Description: ${task.textArea}</li>
<li>Date: ${task.date}</li>
<li>Time: ${task.time}</li>`
noteDiv.appendChild(note_ul);
// if it is not the first element, then remove the class from previous
if (last_ul != null) {
last_ul.classList.remove('fadeInNote');
}
last_ul = note_ul; // this becomes previous for next iteration
taskNotesDiv.appendChild(noteDiv);
}
// remove class of the last element
if (last_ul != null) {
last_ul.classList.remove('fadeInNote');
}
}

How to remove list item using button on said list item

Im building a todo list and Im having trouble figuring out the remove function. I keep getting an error that states "Node not found".
I was coding most a lot of this on my own but I looked up a tutorial for this part. They suggested using:
function removeItem() {
var item = this.parentNode.parentNode;
var parent = this.parentNode;
parent.removeChild(item);
};
I tried to apply it to the code i already had but it doesn't seem to work.
also im not entirely clear on the logic of:
var item = this.parentNode.parentNode;
var parent = this.parentNode;
If someone could also explain what this does also that would be greatly appreciated.
HTML:
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="resources/css/styles.css">
</head>
<body>
<header id="addtodo">
<input type="text" id="input" placeholder="Add an item"/>
<button id="button" type="button">Add item</button>
</header>
<div id="listcontainer">
<ul id="itemlist">
</ul>
</div>
<div id="dividerline">
</div>
<div id="completecontainer">
<ul id="completed">
</ul>
</div>
<script src="resources/JS/code.js"></script>
</body>
JavaScript:
document.getElementById('button').addEventListener('click', function(){
var value = document.getElementById('input').value;
var item = document.createElement("li");
var itemText = document.createTextNode(value);
var itemdiv= document.createElement('div');
var buttons=document.createElement('div');
var text=document.createElement('div');
var remove = document.createElement("button");
var complete = document.createElement("button");
var itemlist = document.getElementById('itemlist');
item.appendChild(itemdiv);
itemdiv.appendChild(text);
text.appendChild(itemText);
itemdiv.appendChild(buttons);
buttons.appendChild(complete);
buttons.appendChild(remove);
remove.innerHTML = 'Remove';
complete.innerHTML = 'Complete';
remove.classList.add('remove');
remove.setAttribute('id','remove');
complete.classList.add('complete');
complete.setAttribute('id','complete');
buttons.classList.add('buttondiv');
text.classList.add('text');
itemdiv.classList.add('itemdiv');
remove.addEventListener('click', removeItem);
complete.addEventListener('click', completeItem);
itemlist.insertBefore(item, itemlist.childNodes[0]);
});
function removeItem() {
var item = this.parentNode.parentNode;
var parent = this.parentNode;
parent.removeChild(item);
};
function completeItem() {
var item = this.parentNode.parentNode;
var parent = this.parentNode;
parent.removeChild(item);
};
I want the remove button to remove the list item its attached to.
The error is in the function
function completeItem() {
var item = this.parentNode.parentNode;
var parent = this.parentNode;
parent.removeChild(item);
};
Swap the item and parent, like so: parent.removeChild(item);
At the first, use console.log() function to debug your code:
function removeItem() {
var item = this.parentNode.parentNode;
var parent = this.parentNode;
console.log( 'item', item ); // => <div class="itemdiv">
console.log( 'parent', parent ); // => <div class="buttondiv">
parent.removeChild(item);
};
As you can see:
1) You mixed up item and parent nodes.
2) If you want to delete a whole <li> element, you have to use more parentNode:
function removeItem() {
var parent = this.parentNode.parentNode.parentNode.parentNode;
var item = this.parentNode.parentNode.parentNode;
console.log( 'item', item ); // => <li>
console.log( 'parent', parent ); // => <ul id="itemlist">
parent.removeChild(item);
};
Or call remove() method right on your item:
function removeItem() {
var item = this.parentNode.parentNode.parentNode;
item.remove();
};
But the best way be using closest() method:
function removeItem() {
var item = this.closest( 'li' );
item.remove();
};
For this case arrows functions are the most easiest way : (and clone node too)
const myButton = document.getElementById('my-button')
, textInput = document.getElementById('text-input')
, ListItems = document.getElementById('itemlist')
, LI_clone4Items = document.querySelector('#clone4Items > li')
var count = 0
myButton.onclick=_=>
{
let newLI = LI_clone4Items.cloneNode(true)
ListItems.insertBefore(newLI, ListItems.childNodes[0])
newLI.querySelector('.text').textContent = textInput.value
newLI.querySelector('.complete').onclick =_=> { ListItems.removeChild(newLI) }
newLI.querySelector('.remove').onclick =_=> { ListItems.removeChild(newLI) }
textInput.value = ''
myButton.disabled = true
}
(textInputControl =_=> { myButton.disabled = (textInput.value.trim()==='') })()
textInput.oninput = textInputControl
<header id="addtodo">
<input type="text" id="text-input" placeholder="Add an item" />
<button id="my-button" type="button">Add item</button>
</header>
<div id="listcontainer">
<ul id="itemlist"></ul>
</div>
<div id="dividerline">
</div>
<div id="completecontainer">
<ul id="completed"></ul>
</div>
<!-- hidden -->
<div style="display:none">
<ul id="clone4Items">
<li>
<div class="itemdiv">
<div class="text"></div>
<div class="buttondiv">
<button class="complete" >Complete</button>
<button class="remove" >Remove</button>
</div>
</div>
</li>
</ul>
The simplest solution is to forget parentNode and just give the new <li> a unique class. Then, you can remove the <li> with the closest() method.
Also, you are creating some unnecessary nodes and should really name the variables more descriptively.
Additionally, you can't have multiple elements with the same id and frankly, you don't need the new elements to have ids in the first place, so forget that.
Lastly, do all the creation and configuration of a new element before moving on to the next one. It makes the code more simple to read and prevents you from forgetting to configure things.
var list = document.getElementById("itemlist");
var todo = document.getElementById('input');
document.getElementById('button').addEventListener('click', function(){
var li = document.createElement("li");
li.textContent = todo.value;
li.classList.add("container");
var itemDiv= document.createElement('div');
var buttonDiv=document.createElement('div');
var removeBtn = document.createElement("button");
removeBtn.textContent = 'Remove';
removeBtn.addEventListener('click', removeItem);
removeBtn.classList.add('remove');
var completeBtn = document.createElement("button");
completeBtn.textContent = 'Complete';
completeBtn.addEventListener('click', completeItem);
completeBtn.classList.add('complete');
// Append your items from the inside out
buttonDiv.appendChild(completeBtn);
buttonDiv.appendChild(removeBtn);
itemDiv.appendChild(buttonDiv);
li.appendChild(itemDiv);
list.insertBefore(li, list.childNodes[0]);
});
function removeItem() {
//Just find the closese ancestor that matches the selector and remove it
this.closest(".container").remove();
};
function completeItem() {
var item = this.parentNode.parentNode;
var parent = this.parentNode;
parent.removeChild(item);
};
<header id="addtodo">
<input type="text" id="input" placeholder="Add an item"/>
<button id="button" type="button">Add item</button>
</header>
<div id="listcontainer">
<ul id="itemlist">
</ul>
</div>
<div id="dividerline">
</div>
<div id="completecontainer">
<ul id="completed">
</ul>
</div>
The problem is how you are trying to capture the list item from the parent function. this.parentNode.parentNode grabs the div item that the button is in. call item.parentNode to get the outer list-item object and instead of removing the item from the parent just remove the whole list-item
document.getElementById('button').addEventListener('click', function(e){
var value = document.getElementById('input').value;
var item = document.createElement("li");
var itemText = document.createTextNode(value);
var itemdiv= document.createElement('div');
var buttons=document.createElement('div');
var text=document.createElement('div');
var remove = document.createElement("button");
var complete = document.createElement("button");
var itemlist = document.getElementById('itemlist');
item.appendChild(itemdiv);
itemdiv.appendChild(text);
text.appendChild(itemText);
itemdiv.appendChild(buttons);
buttons.appendChild(complete);
buttons.appendChild(remove);
remove.innerHTML = 'Remove';
complete.innerHTML = 'Complete';
remove.classList.add('remove');
remove.setAttribute('id','remove');
complete.classList.add('complete');
complete.setAttribute('id','complete');
buttons.classList.add('buttondiv');
text.classList.add('text');
itemdiv.classList.add('itemdiv');
remove.addEventListener('click', removeItem);
complete.addEventListener('click', completeItem);
itemlist.insertBefore(item, itemlist.childNodes[0]);
});
function removeItem() {
var item = this.parentNode.parentNode;
var parent = item.parentNode;
parent.remove()
};
function completeItem() {
var item = this.parentNode.parentNode;
var parent = item.parentNode;
parent.remove()
};
<header id="addtodo">
<input type="text" id="input" placeholder="Add an item"/>
<button id="button" type="button">Add item</button>
</header>
<div id="listcontainer">
<ul id="itemlist">
</ul>
</div>
<div id="dividerline">
</div>
<div id="completecontainer">
<ul id="completed">
</ul>
</div>

How to extract Javascript array information and insert into DOM elements

Initially, I have the following:
<ul id="my_List">
...
</ul>
Using Javascript, I want to generate "li" elements within that ul block that use values for the text information from the array.
For example, I have a template:
<li>
<div>
<a href="#">
<span class="icon"></span>
<span class="text">[PLACEHOLDER HERE]</span>
<span class="icon"></span>
<span class="icon large"></span>
<br/>
<span class="information">[PLACEHOLDER HERE]</span>
<hr />
</a>
</div>
</li>
and I'm trying to figure out how to parse the information from my Javascript array into the [PLACEHOLDER HERE] blocks while still applying the whole template (all the internal tags and classes) in some kind of for loop. Is there a quick way of doing this or will I have to do a series of appends and whatnot to achieve my goal here?
array mapping is another option
var arr = [
{ a: 'foo', b: 'bar' },
{ a: 'foo 2', b: 'bar 2' },
];
var html = arr.map(function(item) {
return '<li>' +
'<span>' + item.a + '<span>' +
'<span>' + item.a + '<span>' +
'</li>';
}).join('');
document.getElementById('#list').innerHTML = html;
<ul id="#list"></ul>
Tried to create a model. Continue like this and create a model like you want.
<script language="JavaScript">
window.onload = function() {
function createTable(tableData) {
var ul = document.getElementById('my_List');
var li = document.createElement('li');
var div = document.createElement('div');
var ahref = document.createElement('a');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('span');
cell.innerHTML = cellData;
row.appendChild(cell);
});
ahref.appendChild(row);
});
div.appendChild(ahref);
li.appendChild(div);
ul.appendChild(li);
}
createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"]]);
}
</script>
So you have an HTML element you want to use as a template -- simply clone it and populate as needed.
$("#create-more").on("click", function() {
// First, save references...
var myContentPane = $(".content-pane");
var myText = $(".form-text").val();
var myInfo = $(".form-info").val();
// This is a clone of our hidden template
var myTemplate = $("#template").clone();
// Replace placeholders in the template...
myTemplate.attr("id", "");
myTemplate.find(".text").text(myText);
myTemplate.find(".information").text(myInfo);
// Now we use the template!
myContentPane.append(myTemplate);
});
#template {
display: none;
}
label {
font-weight: bold;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="text-stuff">Some text:</label>
<input type="text" class="form-text" />
<label for="information">Some Info:</label>
<input type="text" class="form-info" />
<button id="create-more">
Create more
</button>
</form>
<div id="template">
<a href="#"><span class="icon" </span>
<span class="text">[PLACEHOLDER HERE]</span>
<span class="icon"></span>
<span class="icon large"></span>
<br/>
<span class="information">[PLACEHOLDER HERE]</span>
<hr />
</a>
</div>
<section class="content-pane">
</section>
A solution to this problem from scratch can get very messy; I'd recommend you make use of available libraries.
lodash has a great solution called _.template. Check out the docs here.
// constructing string like this for readability
var li = [
'<li>',
'<div><%=id%></div>',
'<div><%=name%></div>',
'</li>'
].join('');
var liTemplate = _.template(li);
var liOne = liTemplate({ id: '1', name: 'Hello' }); // => "<li><div>1</div><div>Hello</div></li>"
var liTwo = liTemplate({ id: '2', name: 'World' }); // => "<li><div>2</div><div>World</div></li>"
EDIT: In order to get those strings into your DOM, you could do the following:
var ul = document.getElementById('my_list');
ul.innerHTML = liOne + liTwo;

How to remove element from array

I have little problem with my code. I push the value of an input in an empty array, and i display the value in a html list with a remove button.
But when i remove the value in html, the array still holds the value. I used arr.splice(0, 1) but it doesn't remove the specific value. Example:
My html list looks like:
v1
v2
v3
My array after the list is filled:
array = [v1, v2, v3]
When i remove v2 in html my array doesn't changes. I'm new to JavaScript.
My code in JSBin or JSFiddle.
im sorry my english is not very nice
https://jsfiddle.net/15mdjdpa/
var taches = [];
var saisie;
var ecran;
var liste;
var organiz;
var j= 0;
function run(){
saisie= document.getElementById('champ').value;
taches.push(saisie);
ecran = document.getElementById('afficheur');
var liste = document.getElementById('listes');
console.log("taches :", taches);
var li = document.createElement('li');
li.setAttribute("id", "lisupr");
var btn = document.createElement('Button');
btn.textContent="X";
btn.addEventListener("click",function supr (){
liste.removeChild(li);
taches.splice(0,1);
console.log("tableau taches: "+ taches);
} );
li.innerText= saisie + " "+" ";
console.log("saisie "+saisie);
li.appendChild(btn);
liste.appendChild(li);
}
<input type ="text" id="champ" onfocus="javascript:this.value=''" class="form-control ">
<button type="button" onclick ="run()" class="btn btn-primary" >send</button>
<div id="afficheur"><h4> list : </h4>
<ul id="listes"> </ul>
</div>
If you want to remove v2 from array, do like this.
var index = array.indexOf(v2);
if(index != -1) array.splice(index,1);
I'd rewrite this code using jQuery. I'd remove all the ids - you can make the edits relative to the button being clicked. Which would let you have more than one of these on a page, among other things.
HTML:
<div class="module">
<input class="item" />
<button type="button" class="btn btn-primary js-add">add</button>
<ul class="list"></ul>
</div>
Here's the script:
var list = [],
addToList = function(target,item){
list.push(item);
target
.append(
$('<li>')
.html(item)
.append(
$('<button>')
.addClass('js-delete m-l')
.html('X')
)
)
}
$('.js-add').click( function(){
var parent = $(this).parent(),
item = parent.find('input.item');
addToList(parent.find('ul.list'),item.val());
item.val('');
})
$('.module').on( 'click', '.js-delete', function(){
var parent = $(this).parent(),
index = $('li').index( parent );
list.splice(index,1);
parent.remove();
console.log(list);
})
Actually, if you want to make it so you can add multiple lists, you actually need to nest the 'list' array in an object or array, and have something reference it, probably inside the module div.
Your issue is what Angular does automatically - without all the management. It binds the html content to the json array so all you need to do is change the array value, or delete it. The HTML would immediately reflect the change.
Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/yducyt83/

Server side pagination with tablesorter - How to refresh it?

I have added a server side pagination with table sorter successfully. I just would like to know how can I refresh it? I would like to create a button to call a refresh function. Does anyone know if there is any method to do it? I do not want to reload the page for it.
UPDATE:
ajaxProcessing: function(data){
if (data && data.hasOwnProperty('rows')) {
var r, row, c, d = data.rows,
total = data.total_rows,
headers = data.headers,
rows = [],
len = d.length;
for ( r=0; r < len; r++ ) {
row = []; // new row array
// cells
for (c in d[r]) {
if (typeof(c) === "string") {
row.push(d[r][c]); //add each table cell data to row array
}
}
rows.push(row); // add new row array to rows array
}
var items="";
$("#tabelaTickets tr:has(td)").remove();
if (rows!==null && rows.length!== 0) {
$.each(rows,function(index,item) {
$("#tabelaTickets").append('<tr class="danger"><td align="center" style="width: 70px"><a type="button" class="btn btn-primary btn-xs" data-placement="right" title="Visualizar ticket" data-toggle="modal" class="btn btn-primary" href="visualizar.php?ticket='+item[3]+'"> #' + item[3] + '</a></td><td><div style="text-overflow:ellipsis;overflow:hidden;width:250px">' + item[4] + '</div></td><td><div style="text-overflow:ellipsis;overflow:hidden;width:350px;">' + item[5] + '</div></td><td><div style="text-overflow:ellipsis;overflow:hidden;width:250px;">' + item[6] + '</div></td><td><div style="text-overflow:ellipsis;overflow:hidden;width:60px;">' + item[7] + '</div></td><td><div style="text-overflow:ellipsis;overflow:hidden;width:70px;">' + item[8] + '</div></td></tr>');
});
}else{
$("#tabelaTickets").append('<tr><td colspan = "6" align="center">SEM RESULTADO A SER EXIBIDO</td></tr>');
}
$("#tabelaTickets").trigger("update");
$("#tabelaTickets").trigger("appendCache");
$("#pleaseWaitDialog").modal('hide');
// in version 2.10, you can optionally return $(rows) a set of table rows within a jQuery object
return [ total];
}
},
Thanks since now,
Erik
your repsonse is JSON, it's easy with a little AJAX function.
example your HTML is look like :
<div class="wrapper">
<div class="item">
<span>item 01</span>
</div>
<div class="item">
<span>item 02</span>
</div>
<div class="item">
<span>item 03 </span>
</div>
</div>
<button class="btn refresh-btn" type="submit"></button>
your response JSON maybe look like :
response = {
{ content : item11 },
{ content : item12 },
{ content : item13 }
};
your HTML render function with AJAX will be look like :
$('.refresh-btn').on('click', function() {
var url = 'yourUrl/?param=refresh&example=true';
var $wrapper = $('.wrapper'); // a div that wrap your new HTML.
$.get(url, {}) //call AJAX GET new item.
.done(function(data) {
$wrapper.html(''); // clear old list;
var $template = $('<div/>', {class : 'item'} ); // create item's HTML.
data.arrayItemList.forEach(function(item) {
var itemTemplate = $template.clone();
itemTemplate.append($('<span/>').text(item.content));
$wrapper.append(itemTemplate); // add new item in list.
});
});
})
that's mean : you create new HTML, and fill it with your data, everything worked fine.
Some time I create a empty template some where in view and clone it.
<div class="sample-template">
<div class="item">
<span> </span>
</div>
</div>
when I need it, I call the jQuery var $template = $('.sample-template').clone(); then fill data with $template.find('span').text(item.content);

Categories