AngularJS, mdList, ng-repeat and generators - angularjs-ng-repeat

Generator:
$scope.inside = [...];
var generator = function*() {
var l = Math.ceil($scope.inside.length / 3);
for (var i = 0; i < 3; i++) {
yield $scope.inside.slice(l * i, l * (i + 1));
}
};
$scope.insideDivided = generator();
Template:
<md-list flex ng-repeat="column in [1,2,3]">
<md-list-item ng-click="log(button.url)" ng-repeat="button in insideDivided.next().value">
{{log(button)}}
{{button.title}}
</md-list-item>
</md-list>
Instruction {{log(button)}} write correct items to console
Object {title: "someTitle1", url: "/inside/fake.html", $$hashKey: "object:13"} root.js:100
Object {title: "someTitle2", url: "/inside/fake.html", $$hashKey: "object:14"} root.js:100
Object {title: "someTitle3", url: "/inside/fake.html", $$hashKey: "object:15"}
....
But only creating empty <md-list>
<!-- ngRepeat: column in [1,2,3] --><md-list flex="" ng-repeat="column in [1,2,3]" role="list" class="ng-binding ng-scope flex">
<!-- ngRepeat: button in insideDivided.next().value -->
</md-list><!-- end ngRepeat: column in [1,2,3] --><md-list flex="" ng-repeat="column in [1,2,3]" role="list" class="ng-binding ng-scope flex">
<!-- ngRepeat: button in insideDivided.next().value -->
</md-list><!-- end ngRepeat: column in [1,2,3] --><md-list flex="" ng-repeat="column in [1,2,3]" role="list" class="ng-binding ng-scope flex">
<!-- ngRepeat: button in insideDivided.next().value -->
</md-list><!-- end ngRepeat: column in [1,2,3] -->
Why ng-repeat work, but don't create md-list-items?

ng-repeat isn't aware of generators. You need to convert it to an array first and iterate over that.
Here is the issue on github. https://github.com/angular/angular.js/issues/15202
It looks like they won't be supported anytime soon either.

Related

Grails, sorting and filtering a grid at the same time using ajax

I have a grid(html-table) with a lot of columns and want to combine filtering and sorting on this table.
At the moment I only use filtering on one column but sorting on several columns.
I want to do this with ajax.
I read an article [http://www.craigburke.com/2011/01/23/grails-ajax-list-with-paging-sorting-and-filtering.html]
and tried to adapt it to my version of grails-3.2.6.
This has been very hard to solve and now I'm totally stuck.
If I add something in the filter nothing happens but when I click on a column, the filtering takes place and also sorting, clicking a second time, ajax is not called and the filter is overwritten with the default value. I have managed to implement it on a test project which act the same.
It is much code and maybe there is a way to include the whole project in this question in some way?
I'll try to show most of the important part here if it could help.
The index.gsp:
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />
<g:set var="entityName" value="${message(code: 'person.label', default: 'Person')}" />
<title><g:message code="default.list.label" args="[entityName]" /></title>
<script type="text/javascript">
$(document).ready(function() {
setupGridAjax();
setupFilterAjax();
});
</script>
<script type="text/javascript">
function setupGridAjax() {
$('#gridPersons').find('.paginateButtons a, th.sortable a').on('click', function(event) {
event.preventDefault();
var url = $(this).attr('href');
var grid = $(this).parents("table.ajax");
$(grid).html($("#spinner").html());
$.ajax({
type: 'GET',
url: url,
data: [tag],
success: function(data) {
$(grid).fadeOut('fast', function() {$(this).html(data).fadeIn('slow');});
}
})
});
}
</script>
<script type="text/javascript">
// Turn any input changes or form submission within a filter div into an ajax call
function setupFilterAjax(){
alert('FILTER--Anropat');
$('div.filters select:input').on('change',function(event) {
var filterBox = $(this).parents("div.filters");
filterGrid(filterBox);
});
$("div.filters form").submit(function() {
var filterBox = $(this).parents("div.filters");
alert('FILTERBOX - '+filterBox);
filterGrid(filterBox);
return false;
});
}
// Reload grid based on selections from the filter
function filterGrid(filterBox) {
alert('FILTER-change detected');
var grid = $(filterBox).next("div.gridPersons");
$(grid).html($("#spinner").html());
var form = $(filterBox).find("form");
var url = $(form).attr("action");
var data = $(form).serialize();
alert('FILTERGRID - '+url);
$.ajax({
type: 'POST',
url: '${g.createLink( controller:'person', action:'index' )}',
data: [tag],
success: function(data) {
$(grid).fadeOut('fast', function() {$(this).html(data).fadeIn('slow');});
}
});
}
</script>
</head>
<body>
<g:message code="default.link.skip.label" default="Skip to content…"/>
<div class="nav" role="navigation">
<ul>
<li><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></li>
<li><g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link></li>
</ul>
</div>
<div id="list-person" class="content scaffold-list" role="main">
<h1><g:message code="default.list.label" args="[entityName]" /></h1>
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<div class="filters">
<g:form action="register">
<div id="selectMill">
Select tags:
<g:select class="selected" name="tag" from="${tagList}" value="${filters?.tag}" noSelection = "${['':'All']}" optionValue="" optionKey="" />
</div>
<div id="gridPersons">
<g:render template="Grid_Persons" model="personList" />
</div>
<div class="pagination">
<g:paginate total="${personCount ?: 0}" />
</div>
<fieldset class="buttons">
<input class="save" type="submit" value="${message(code: 'offer.create.from.buffer.label', default: 'Create')}" />
</fieldset>
</g:form>
</div>
</div>
</body>
The template: _Grid_Persons.gsp
<table class="ajax">
<thead>
<tr>
<g:sortableColumn property='reg' title='Register' />
<g:sortableColumn property="id" title='Id' params="${filters}"/>
<g:sortableColumn property='name' title='Name' params="${filters}"/>
<g:sortableColumn property='tag' title='Tag' params="${filters}"/>
<g:sortableColumn property='registered' title='Registered' params="${filters}"/>
</thead>
<tbody>
<g:each in="${personList}" status="i" var="ps">
<tr class="${ (i % 2) == 0 ? 'even': 'odd'}">
<td><g:checkBox name="ckb" value="${ps.id}" checked="false" /></td>
<td><g:link action="edit" id="${ps.id}">${ps.id}</g:link></td>
<td>${ps.name}</td>
<td>${ps.tag}</td>
<td>${ps.registered}</td>
<td>
</g:each>
</tbody>
The index-part of the controller:
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
def tagList = Person.withCriteria {
projections {
distinct("tag")
}
}
def List<Person> personList = getPersonList()
// Paging def prodBuffer = getPaginatedList(prodBuffer, max, params.offset?.toInteger())
def filters = [tag: params.tag, sort: params.sort, order: params.order]
def model = [personList: personList, filters:filters, tagList:tagList]
if (request.xhr) {
println("AJAX-Request!!!")
render(template:"Grid_Persons", model:model)
prodBuffer, offerDetails:offerDetails, filters:filters])
} else {
offerDetails: offerDetails, millList: millList, selectedMill:false, prodBufferCount: ProdBuffer.count()]
[personList:personList,tagList:tagList]
}
Person.count(), tagList:tagList]
}
def List<Person> getPersonList() {
println("getPersonList tag: "+params.tag)
def tag = params.tag
def c = Person.createCriteria()
def tempList = c.list {
if (tag) eq("tag", tag)
if (params.sort){
order(params.sort, params.order)
}
}
return tempList
}
From debugging:
The page is loaded:
getPersonList tag: null
Selected "Grails" in the filter:
getPersonList tag: Grails
AJAX-Request!!!
Klicked on the "Name"-column header
getPersonList tag: Grails
AJAX-Request!!!
-- Now the list is sorted(ascending) and filtered
Klicked on the column again:
getPersonList tag: Grails
-- Now the list is resorted(descending) and the filtering still ok but the SELECT TAGS now view "All"
Klicked the column for the third time:
getPersonList tag:
AJAX-Request!!!
-- Now the list show all lines and resorted(ascending)
Now solved by using the recommended plugin - datatables.
In case you are in a hurry you can inject https://datatables.net/ that adds the utilities you require among others

Bootstrap modal images not working - Multiple

I just followed w3school tutorial for this bootstrap modal image. I have two image cards in my page. So I need to popup that two images. But it's working with one image only.
Link to w3school article
<!-- Trigger the Modal -->
<img id="myImg" src="http://d14dsi4x2zx6ql.cloudfront.net/files/styles/welcome_image/public/VCW_TI_5_BayLoop_Hero_Manley_1280x642_sized.jpg?itok=EaARDZt8" alt="">
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- The Close Button -->
<span class="close" onclick="document.getElementById('myModal').style.display='none'">×</span>
<!-- Modal Content (The Image) -->
<img class="modal-content" id="img01">
<!-- Modal Caption (Image Text) -->
<div id="caption"></div>
</div>
I insert "myImg" id in my other image, but it didn't work. First image popup worked as I expect. What will be missing here?
You can't give two elements the same id
if you want to do the same action for both you can give them class
<img class="myImg" src="http://placehold.it/850x450" alt="image1" width="200">
<img class="myImg" src="http://placehold.it/700x400/f00" alt="image2" width="200">
and js will be:
// Get the modal
var modal = document.getElementById('myModal');
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementsByClassName('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
//iterate over img to add click event for each one,, jquery will make it much easier
for(var i=0;i< img.length;i++){
img[i].onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
}
//jquery option
/*$('.myImg').on('click', function(){
modal.style.display = "block";
modalImg.src = $(this).attr('src');
captionText.innerHTML = $(this).attr('alt');
})*/
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
Demo
Id must be unique, See an example here. https://fiddle.jshell.net/wg5p60g7/

selecting span - css selectors - Ruby

I am trying to select and click on this <span>
<span class="el-icon 28-0"></span>
in the below hierarchy but unable to do so.
<div class="list-wrap ng-scope" ng-repeat="d in cols">
<div class="list-element selected" ng-click="a.cb(d.name, member.name)" ng-class="{selected: (selectValue === d.name || selectValue === member.name + ' ' + d.name)}">
<span class="el-icon 28-0"></span>
<!-- ngIf: !d.displayName --><span ng-if="!d.displayName" class="el-text ng-binding ng-scope">
28.0
</span><!-- end ngIf: !d.displayName -->
<!-- ngIf: d.displayName -->
</div>
</div>
<div class="list-wrap ng-scope" ng-repeat="d in cols">
<div class="list-element" ng-click="a.cb(d.name, member.name)" ng-class="{selected: (selectValue === d.name || selectValue === member.name + ' ' + d.name)}">
<span class="el-icon 27-0"></span>
<!-- ngIf: !d.displayName --><span ng-if="!d.displayName" class="el-text ng-binding ng-scope">
27.0
</span><!-- end ngIf: !d.displayName -->
<!-- ngIf: d.displayName -->
</div>
</div>
This is the page , I am referencing
https://docs.saucelabs.com/reference/platforms-configurator/?_ga=1.5883444.608313.1428365147#/
In "Browser" section, I am trying to select FF 28.0
I've tried
#driver.find_element(:css,"span.el-icon.28-0")
BUt it gives
The given selector span.el-icon.28-0 is either invalid or does not result in a WebElement.
Tried this too
#driver.find_element(:css,"span.el-text.ng-binding.ng-scope").click
which gives
Element is not currently visible and so may not be interacted with
Valid CSS classes cannot start with a number.
If changing the class name is not an option for you, try changing the selector to span.el-icon[class*="28-0"]
Note: The 'contains' selector [class*=...] matches any elements whose given attribute contains the given value. In this case, any element with a class attribute containing '28-0' would be matched. You could also do this with things like alt, src or href to match external images or links. Read more here.

Conditional display with Dojo MVC

I have a dojox/mvc/Repeat area which is bound to an array of records.
Within the row of the Repeat there is a field (the id of the record) which should be a simple display Output if the record has already been saved to the database, but it should be a TextBox if the record is new (the user must enter the value).
How do I solve this elegantly? I am fairly new to Dojo and its MVC part is very under-documented.
The most MVC-ish solution I have found so far is as follows:
1)
I put a "hasBeenSaved" property into the model which will mark the server-side saved state of the record. This attribute will be bound to the view with a transformation since the "display" style attribute of the DIV will be bound to the hasBeenSaved model attribute (one is a boolean the other is a string: "block"/"none").
2)
Within the Row, I put a conditionally visible div around the id input field. This will be visible only when the record is new, so its display style attribute is bound with an appropriate transformer attached to the Dojo MVC binding.
The same is done for the id output field but the transformer is different on the binding since this will be displayed only when the record has already been saved.
The JSFiddle which I have used to prototype this solution: http://jsfiddle.net/asoltesz/6t4dj1w7/15/
require([
"dojo/_base/declare", "dojo/dom-style", "dojo/parser", "dojo/ready",
"dijit/_WidgetBase", "dijit/_TemplatedMixin",
'dojox/mvc/getStateful'
], function(
declare, domStyle, parser, ready,
_WidgetBase, _TemplatedMixin,
getStateful
){
// setting up the data model for MVC
model = {
items: [
{ id: 'id1',
hasBeenSaved: true
},
{ id: null,
hasBeenSaved: false
},
{ id: null,
hasBeenSaved: false
},
{ id: 'id3',
hasBeenSaved: true
}
]
};
model = getStateful(model);
/**
* This mixin makes it possible to set the "display" style property of
* the DOM node (of any widget) as a Widget property and thus bind it to an MVC model
* when needed.
*/
declare("_DisplayAttributeMixin", [], {
// parameters
display: "block",
_setDisplayAttr: function(/*String*/ display){
this._set("display", display);
domStyle.set(this.domNode, "display", display);
}
});
/** Transformer methods for converting hasBeenSaved to visible/hidden values */
transfSavedToHidden = {format: function(hasBeenSaved){
console.log("transfSavedToHidden: " + (hasBeenSaved ? "none" : "block"));
return hasBeenSaved ? "none" : "block";
}};
transfSavedToVisible = {format: function(hasBeenSaved){
console.log("transfSavedToHidden: " + (hasBeenSaved ? "block" : "none"));
return hasBeenSaved ? "block" : "none";
}};
ready(function(){
// Call the parser manually so it runs after our mixin is defined, and page has finished loading
parser.parse();
});
});
The HTML markup:
<script type="dojo/require">at: "dojox/mvc/at"</script>
<div
data-dojo-type="dojox/mvc/Group"
data-dojo-props="target: model"
>
<div id="repeatId"
data-dojo-type="dojox/mvc/Repeat"
data-dojo-props="children: at('rel:', 'items')"
>
<div
data-dojo-type="dojox/mvc/Group"
data-dojo-props="target: at('rel:', ${this.index})"
>
<span>Record: ${this.index}</span>
<!-- This is displayed only when the record is new (not saved yet) -->
<div
data-dojo-type="dijit/_WidgetBase"
data-dojo-mixins="_DisplayAttributeMixin"
data-mvc-bindings="
display: at('rel:', 'hasBeenSaved')
.direction(at.from)
.transform(transfSavedToHidden)"
>
<label for="idInput${this.index}">id:</label>
<input
data-dojo-type="dijit/form/TextBox"
id="idInput${this.index}"
data-dojo-props="value: at('rel:', 'id')"
></input>
</div> <!-- end conditionally hidden div -->
<!-- This is displayed only when the record has already been saved -->
<div
data-dojo-type="dijit/_WidgetBase"
data-dojo-mixins="_DisplayAttributeMixin"
data-mvc-bindings="
display: at('rel:', 'hasBeenSaved')
.direction(at.from)
.transform(transfSavedToVisible)"
>
<label for="idInput${this.index}">id:</label>
<span
data-dojo-type="dojox/mvc/Output"
id="idOutput${this.index}"
data-dojo-props="value: at('rel:', 'id')"
></span>
</div> <!-- end conditionally hidden div -->
<hr/>
</div> <!-- end of row -->
</div> <!-- end of Repeat -->
</div> <!-- end of Group -->
A secondary, less complex solution:
Bind the "hasBeenSaved" property to a hidden text within the repeating div.
Put an onChange event on the hidden field which gets the index of the repeat as well.
The onChange event simply hides the field which is not appropriate in light of the hasBeenChanged property value for the record.
The fiddle is here: http://jsfiddle.net/asoltesz/8u9js6sz/5/
Code:
hasBeenSavedChanged = function(field, index) {
var divToHide
if (field.value == true) {
divToHide = "idInputDiv"
}
else {
divToHide = "idOutputDiv"
}
var div = document.getElementById(divToHide + index);
div.style.display = "none";
}
require([
"dojo/_base/declare", "dojo/dom-style", "dojo/parser", "dojo/ready",
"dijit/_WidgetBase", "dijit/_TemplatedMixin",
'dojox/mvc/getStateful'
], function(
declare, domStyle, parser, ready,
_WidgetBase, _TemplatedMixin,
getStateful
){
// setting up the data model for MVC
model = {
items: [
{ id: 'id1',
hasBeenSaved: true
},
{ id: null,
hasBeenSaved: false
},
{ id: null,
hasBeenSaved: false
},
{ id: 'id3',
hasBeenSaved: true
}
]
};
model = getStateful(model);
ready(function(){
// Call the parser manually so it runs after our mixin is defined, and page has finished loading
parser.parse();
});
});
HTML:
<script type="dojo/require">at: "dojox/mvc/at"</script>
<div
data-dojo-type="dojox/mvc/Group"
data-dojo-props="target: model"
>
<span id="itemsCtl"
data-dojo-type="dojox/mvc/ListController"
data-dojo-props="model: model.items">
</span>
<div id="itemsRepeat"
data-dojo-type="dojox/mvc/Repeat"
data-dojo-props="children: at('rel:', 'items')"
>
<div
data-dojo-type="dojox/mvc/Group"
data-dojo-props="target: at('rel:', ${this.index})"
>
<span>Record: ${this.index}</span>
<input
id="hasBeenChanged${this.index}"
data-dojo-type="dijit/form/TextBox"
data-dojo-props="value: at('rel:', 'hasBeenSaved')"
onChange="hasBeenSavedChanged(this, '${this.index}');"
type="hidden"
></input>
<!-- This is displayed only when the record is new (not saved yet) -->
<div id="idInputDiv${this.index}"
>
<label for="idInput${this.index}">id:</label>
<input
data-dojo-type="dijit/form/TextBox"
id="idInput${this.index}"
data-dojo-props="value: at('rel:', 'id')"
></input>
</div> <!-- end conditionally hidden div -->
<!-- This is displayed only when the record has already been saved -->
<div id="idOutputDiv${this.index}" >
<label for="idInput${this.index}">id:</label>
<span
data-dojo-type="dojox/mvc/Output"
id="idOutput${this.index}"
data-dojo-props="value: at('rel:', 'id')"
></span>
</div> <!-- end conditionally hidden div -->
<hr/>
</div> <!-- end of row -->
</div> <!-- end of Repeat -->
</div> <!-- end of Group -->
Mixin/transformer approach is something I had in mind, too. Two things I’d add there are out-of-the-box Dijit features, one is dijitDisplayNone class, another is attribute mapping feature.
Though it’s strange that the former is undocumented, the intent may have been for private usage within Dijit codebase.
Though it’s a bit hackish (and may be broken in future 1.x Dijit releases), overriding the Dijit code that’s responsible for attribute mapping will allow you to map a widget attribute to a CSS class that’s toggled.
Here’s a code sample that uses the above two:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/dojo/1.10.1/dojo/resources/dojo.css">
<link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/dojo/1.10.1/dijit/themes/dijit.css">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/dojo/1.10.1/dojo/dojo.js" data-dojo-config="async: 1, parseOnLoad: 0"></script>
<script type="text/javascript">
require([
"dojo/_base/array",
"dojo/_base/declare",
"dojo/_base/lang",
"dojo/dom-class",
"dojo/parser",
"dojox/mvc/getStateful",
"dijit/form/TextBox"
], function(array, declare, lang, domClass, parser, getStateful){
declare("CssToggleMixin", null, {
// summary:
// Mixin class to support widget attributes with toggleClass type.
// toggleClass type allows boolean value of an attribute to reflect existence of a CSS class in a DOM node in the widget.
_attrToDom: function(/*String*/ attr, /*String*/ value, /*Object?*/ commands){
// summary:
// Handle widget attribute with toggleClass type.
// See dijit/_WidgetBase._attrToDom() for more details.
var callee = arguments.callee;
array.forEach((function(){ return lang.isArray(commands) ? commands.slice(0) : [commands]; })(arguments.length >= 3 ? commands : this.attributeMap[attr]), function(command){
command.type != "toggleClass" ?
this.inherited("_attrToDom", lang.mixin([attr, value, command], {callee: callee})) :
domClass.toggle(this[command.node || "domNode"], command.className || attr, value);
}, this);
}
});
flipConverter = {
format: function (value) {
return !value;
},
parse: function (value) {
return !value;
}
};
model = getStateful({
items: [
{
value: "Foo",
hasBeenSaved: true
},
{
hasBeenSaved: false
},
{
hasBeenSaved: false
},
{
value: "Bar",
hasBeenSaved: true
}
]
});
parser.parse();
})
</script>
</head>
<body>
<script type="dojo/require">at: "dojox/mvc/at"</script>
<div data-dojo-type="dojox/mvc/WidgetList"
data-dojo-mixins="dojox/mvc/_InlineTemplateMixin"
data-dojo-props="children: at(model, 'items')">
<script type="dojox/mvc/InlineTemplate">
<div>
<span data-dojo-type="dijit/_WidgetBase"
data-dojo-mixins="CssToggleMixin"
data-dojo-props="value: at('rel:', 'value'),
noDisplay: at('rel:', 'hasBeenSaved').transform(flipConverter),
_setValueAttr: {node: 'domNode', type: 'innerText'},
_setNoDisplayAttr: {type: 'toggleClass', className: 'dijitDisplayNone'}"></span>
<span data-dojo-type="dijit/form/TextBox"
data-dojo-mixins="CssToggleMixin"
data-dojo-props="value: at('rel:', 'value'),
noDisplay: at('rel:', 'hasBeenSaved'),
_setNoDisplayAttr: {type: 'toggleClass', className: 'dijitDisplayNone'}"></span>
</div>
</script>
</div>
</body>
</html>
Hope it’ll shed some light.
Best, Akira

Django with Ajax and jQuery

I would like after clicking on one of the many Item shown a window with his description (single item description).
How to create this using Ajax and jQuery with Django?
model:
class Item(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField()
price = models.DecimalField(max_digits=5, decimal_places=2)
desc = models.TextField()
views:
def item_list(request):
items = Item.objects.all()[:6]
return render_to_response('items.html', {'items':items}, context_instance=RequestContext(request))
def single_item(request, slug):
item = Item.objects.get(slug=slug)
return render_to_response('single.html', {'item':item}, context_instance=RequestContext(request))
template:
<!-- Single item description: -->
<div id="description">
<img src="/site_media/images/photo.png">
<div id="item_description">
<input name="add" type="button" id="add" value="Add to Cart">
<p class="title">Single Item name</p>
<p class="description"><span>Description:</span>
This is single item description
</p>
</div>
</div>
<!-- All item: -->
<div id="item">
{% for i in items %}
<div class="item">
<img src="/{{ i.image.url }}" />
<p>
<span> {{ i.name }} </span>
<span> {{i.price}} </span>
</p>
</div>
{% endfor %}
</div>
</div>
</div>
If you want to use ajax to refresh your page, you'll need to do three things:
Add an entry to urls.py for the ajax call (or add a condition to your view function to process the request if it's ajax)
Add the javascript block to make the ajax call and update the html/text with the new data
Add the code in your views.py to handle the ajax call and respond with json data
urls.py
...
url(r'/ajax-view-single/)/$', 'ajax_single_item', name='app_name_ajax_single_item'),
html/js
<script type="text/javascript" src="/js/json2.js"></script>
$("#view-single-item").click(function () {
try {
// get slug from html
var slug = "";
var data = {
slug: slug
};
$.get('{% url app_name_ajax_single_item %}', data, function(data){
// your data returned from django is in data
alert(data.item_name);
}, 'json');
//$('#error').hide();
}
catch(err) {
$('#error').html(err);
$('#error').show();
}
return false;
});
views.py
from django.http import HttpResponse
from django.utils import simplejson
from django.shortcuts import get_object_or_404
def ajax_single_item(request):
'''gets single item'''
if not request.is_ajax():
return HttpResponse(simplejson.dumps({'result': False}))
# get slug from data
slug = request.GET.get('slug', None)
# get item from slug
item = get_object_or_404(Item, slug=slug)
return HttpResponse(simplejson.dumps({
'result': True,
'item_name': item.name,
'item_price': item.price,
'item_desc': item.desc,
'item_slug': item.slug
}))

Resources