I have a list where a user can save various items in a Django app. Next to each items I have a button that can be used to delete this item.
Items are stored in a database and are displayed with a for loop. The problem is whatever button I press, the first one is selected and deleted.
I am new to JavaScript but I do understand that my issue is coming from my var.product selector because .val() returns the first element that matches ('.substitut').
I have tried to tweak a little with $(this) but with no luck...
How can I select each product in each button individually?
My HTML:
{% extends 'finder/base.html' %}
{% block content %}
<header class="masthead" id='fav_list'>
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center" style="color: beige;">Bienvenue sur ton compte {{ user }}</h2>
<hr class="divider1 my-4" />
<div class='w-75 mx-auto row d-flex justify-content-around mb-3'>
<h3 class="intro-text text-center account_items" style="color: beige;">Produit recherché</h3>
<h3 class="intro-text text-center account_items" style="color: beige;">Produit de substitut</h3>
</div>
</div>
<div class="w-75 mx-auto container-fluid" style='background-color: transparent;'>
{% for saved in saved_list %}
<div class='row d-flex justify-content-between'>
<div class="card mb-3" style="width: 49%;">
{...}
</div>
<div class="card mb-3" style="width: 49%;">
<div class="row no-gutters">
<div class="col-md-2 my-auto">
<img class="mx-auto d-block " style="width:auto; height:auto; max-width:100px; max-height:100px; "
src="{{ saved.sub_product.picture }}">
</div>
<div class="col-md-9">
<div class="card-body">
<h5 class="card-title"><a href="{% url 'finder:detail' saved.sub_product.id %}"
class="aaccount">{{ saved.sub_product.real_name}}/ {{ saved.sub_product.real_brand }}</a>
</h5>
<img src="/static/finder/img/nutriscore-{{ saved.sub_product.nutrition_grade}}.svg"
style="width:70px;"><br>
</div>
</div>
<div class="col-md-1 my-auto mx-auto">
<form class="form_id" method='post'>{% csrf_token %}
<button class=' btn substitut' value='{{ saved.id }}'><i class='fas fa-trash-alt'></i></button>
</form>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
<div class="pagination">
<nav aria-label="">
<ul class="pager mb-1">
{% if saved_list.has_previous %}
<span>previous</span>
{% endif %}
<span class="current" style='color:white;'>
Page {{ saved_list.number }} de {{ saved_list.paginator.num_pages }}
</span>
{% if saved_list.has_next %}
<span>next</span>
{% endif %}
</ul>
</nav>
</div>
</header>
{% endblock %}
My AJAX:
$(".form_id").on('submit', function(event) {
event.preventDefault();
var product = $('.substitut').val();
console.log(product);
var url = '/register/delete/';
$.ajax({
url: url,
type: "POST",
data:{
'product': product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
console.log(product);
$("#fav_list").load(location.href + " #fav_list > *");
location.reload(true);
}
});
});
You can use onclick event of jquery instead of submit , because as i can see in your code provided you are not submiting your form and inside your submit event you are using ajax so this should work.Change your ajax code like below :
$(".substitut").on('click', function(event) {
event.preventDefault();
//getting current button value which is clicked
var product = $(this).val();
console.log(product);
var url = '/register/delete/';
//put your ajax code here
});
Demo code :
$(".substitut").on('click', function(event) {
event.preventDefault();
//getting current button value which is clicked
var product = $(this).val();
console.log(product);
var url = '/register/delete/';
//put your ajax code here
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='substitut' value='{{ saved.id}}'><i class='fas fa-trash'></i></button>
<button class='substitut' value='{{ saved.id1}}'><i class='fas fa-trash'></i></button>
<button class='substitut' value='{{ saved.id2}}'><i class='fas fa-trash'></i></button>
Update 1: Alternate solution would be creating a click event on button which will store current reference of button clicked and used that inside your submit event .
Demo code :
var $submit = null;
var $button = $('button');
$(".form_id").on('submit', function(event) {
event.preventDefault();
//getting value of button clicked
var product = $submit.value;
console.log(product);
var url = '/register/delete/';
$.ajax({
url: url,
type: "POST",
data: {
'product': product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype: 'json',
success: function(data) {
if (data['success'])
console.log(product);
$("#fav_list").load(location.href + " #fav_list > *");
}
});
});
//when button is clicked
$button.click(function(event) {
//putting current button clicked reference in variable $submit
$submit = this;
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form_id" method='post'>{% csrf_token %}{{ saved.id}}
<button class='substitut' value='{{ saved.id}}'><i class='fas fa-trash'></i></button>
</form>
<form class="form_id" method='post'>{% csrf_token %}{{ saved.id1}}
<button class='substitut' value='{{ saved.id1}}'><i class='fas fa-trash'></i></button>
</form>
Related
I am having issues with individual upload cancels for blueimp jquery fileupload library, have gone through the library and the functionality isn't well documented. I don't know if anyone also has an experience with blueimp fileupload, please help me out:
The code for the Upload is:
'use strict';
$(function (){
function previewDataDetail(img,imgSize,imgName){
return `
<div class="col-sm-12" id="progress_img">
<img src="${img}">
<span>${imgSize}</span>
<div class="value_hold" style="display:none">
<p id="preview_name">${imgName}</p>
</div>
<button class="btn btn-dark">Cancel</button>
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" id="progress_bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style= "width:100%"></div>
</div>
</div>
`
}
function abortUpload(e){
e.preventDefault();
var template = $(e.currentTarget).closest(
'#progress_img'
),
data = template.data('data') || {};
data.context = data.context || template;
if (data.abort) {
data.abort();
} else {
data.errorThrown = 'abort';
this._trigger('fail', e, data);
}
}
$("#uploadTrigger").click(function(){
// const url = "{% url 'property_pic' %}";
// const csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
// $("#fileupload").attr('data-url', url);
// $("#fileupload").attr('data-form-data', csrf_token);
$("#fileupload").click()
});
$("#fileupload").fileupload({
dataType: 'json',
sequentialUploads: true,
add: function(e,data){
var previewImg = data.files[0];
var previewUrl = URL.createObjectURL(previewImg);
$("#formInput").append(previewDataDetail(previewUrl,previewImg.size,previewImg.name))
data.context = $("#progress_img #progress_bar")
data.submit();
var jqXHR = data.submit().error(function (jqXHR, textStatus, errorThrown){
if (errorThrown === 'abort'){
alert('This upload has been cancelled')
}
})
$("#progress_img button").click((e) => {
e.preventDefault();
jqXHR.abort()
const snip = e.currentTarget.closest("#progress_img preview_name")
console.log(snip);
// data.originalFiles.forEach(i => {
// if(i.name == e.target.closest('.value_hold'))console.log(previewImg.name);
// })
// console.log(e.currentTarget.closest('#progress_img'));
e.target.closest('#progress_img').remove()
})
},
progress: function(e,data){
var progress = parseInt((data.loaded / data.total) * 100, 10);
// console.log(data.context.closesr("#progress-bar"))
data.context.css("width", progress + "%");
data.context.attr('aria-valuenow', progress + "%")
},
done: function(e, data){
$("#progress_img").remove()
if (data.result.is_valid){
console.log('I got saved to the db')
}else{
const error = data.result.message
console.log(error)
if(error){
$(`<p class="alert alert-danger">${error}</p>`).insertBefore($("#formInput"))
}
let replacer = $(".alert")
if(replacer.length > 1){
replacer.remove();
$(`<p class="alert alert-danger">${error}</p>`).insertBefore($("#formInput"))
}
}
}
})
})
The code for the template:
{% extends 'shared/base_profile.html'%}
{% load static %}
{% load crispy_forms_tags %}
{% block title %}
Upload Property Pictures
{% endblock title %}
{% block content %}
<div class="row" id="formHolder">
<div class="col-sm-8" id="formCont">
<form id="formInput" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% if form %}
<div id="uploader_expand">
<label>{{form.images.label}}</label>
{{form.images}}
</div>
{% endif %}
<!-- <input type="hidden" id="delUpload" name="filesort"> -->
<!-- <input type="submit" value="Upload" id="submit" class="btn btn-primary"> -->
</form>
<button class="btn btn-primary" id="uploadTrigger"><span class="glyphicon glyphicon-cloud-upload">Upload photos</span></button>
<!-- <div id="alertMsg" class="alert" style="display: block;"></div> -->
</div>
<div class="col-sm-4">
</div>
</div>
<div class="row" id="confirmRow">
<!-- <div class="col-sm-8 hidden" id="confirm">
<label class="hidden" id="confirmerLabel">Finished Preview</label>
<input type="checkbox" class="hidden" id="confirmer">
</div> -->
<div class="col-sm-4">
<!-- For Search Field etc -->
</div>
</div>
<div class="row" >
<div class="col-sm-8" id="upload_row">
{% if images %}
{% if images|length == 1 %}
<div class="col-sm-3" id="uploaded_files">
<img src="{{image.images.url}}" alt="{{images.post.slug}}">
</div>
{% elif images|length > 1 %}
{% for image in images %}
<div class="col-sm-3" id="uploaded_files">
<img src="{{image.images.url}}" alt="{{image.post.slug}}">
</div>
{% endfor %}
{% endif %}
{% endif %}
</div>
<div class="col-sm-4">
<!-- For Search Field -->
</div>
</div>
{% endblock content %}
I have this view.html with Django:
{% for item in cart %}
<div class="card rounded-3 mb-4">
<div class="card-body p-4">
<div class="row d-flex justify-content-between align-items-center">
<div class="col-md-2 col-lg-2 col-xl-2">
<img
src="{{ item.product.product_image.url }}"
class="img-fluid rounded-3" alt="Cotton T-shirt">
</div>
<div class="col-md-3 col-lg-3 col-xl-3">
<p class="lead fw-normal mb-2">{{ item.product.name }}</p>
<p><span class="text-muted">
{% if item.product.is_service %}
Service
{% else %}
Product
{% endif %}
</span> <span class="text-muted">
</div>
<div class="col-md-3 col-lg-2 col-xl-2 d-flex product_data">
<input type="hidden" value="{{ item.product_id }}" class="prod_id">
{% csrf_token %}
{% if item.product.is_service == False %}
{% if item.product.quantity >= item.product_quantity %}
<div class="container">
<div class="row">
<div class="col-lg-2">
<div class="input-group">
<span class="input-group-btn">
<button type="button"
class=" changeQuantity quantity-left-minus btn btn-primary btn-number"
data-type="minus">
<span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<input type="number" id="quantity"
class=" align-items-center qty-input"
value="{{ item.product_quantity }}">
<span class="input-group-btn">
<button type="button"
class="changeQuantity quantity-right-plus btn btn-primary btn-number"
data-type="plus">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
</div>
</div>
{% else %}
<h4>Out of Stock</h4>
{% endif %}
{% endif %}
</div>
<div class="col-md-3 col-lg-2 col-xl-2 offset-lg-1">
<h5 class="mb-0">$ {{ item.product.selling_price }}</h5>
</div>
<div class="col-md-1 col-lg-1 col-xl-1 text-center">
<button class="text-danger delete_cart_item">Remove</button>
</div>
</div>
</div>
</div>
{% endfor %}
And here is the jQuery code:
// change the quantity in the cart
$('.changeQuantity').click(function(e) {
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val()
var product_qty = $(this).closest('.product_data').find('.qty-input').val()
var token = $('input[name=csrfmiddlewaretoken]').val()
$.ajax({
method: 'POST',
url: '/update_cart/',
data: {
'product_id': product_id,
'product_qty': product_qty == null ? 1 : product_qty,
csrfmiddlewaretoken: token
},
success: function(response) {
console.log(response.status)
alertify.success(response.status)
// $('.cart-data').load(location.href + " .cart-data")
}
})
});
//delete
// change the quantity in the cart
$('.delete_cart_item').click(function(e) {
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val()
var token = $('input[name=csrfmiddlewaretoken]').val()
$.ajax({
method: 'POST',
url: '/delete_cart/',
data: {
'product_id': product_id,
csrfmiddlewaretoken: token
},
success: function(response) {
console.log(response.status)
alertify.success(response.status)
// $('.cart-data').load(location.href + " .cart-data")
}
})
})
in the first code for (changeQuantity) I could access the product_id... but with the second I couldn't it is just (undefined) ??? ..... but when change the second one to
var product_id = $('.prod_id').val()
I access it successfully...
my question is why? it is just a same file and code?
and is there a better way to work with those thinks in jquery
.product_data is an ancestor of .changeQuantity so you can use closest to go from .changeQuantity to .product_data but .product_data is not an ancestor of .delete_cart_item so you cant use closet to select it.
The parent div of .delete_cart_item is a sibling of .product_data so you can use the method below to get uoyr data.
var product_id = $(this).parent().prevAll('.product_data').find('.prod_id').val()
I work with Symfony and Twig. I currently have a twig page containing a list of products, I display them with a foreach loop and I put pagination to limit the display of products.
I have a form in this page with a checkbox as input and I need to keep my checkbox checked save in session when I go to the next page
I tried to do it with adding this code
there is some code, I added some comment in the pagination view and controller to explain what I tried.
view of my loop :
<form>
<div class="row" >
{% for annonce in annonces %}
<div class="col-12 col-md-6 col-lg-4">
<p class="text text--blue text--bold m-0 text--medium mt-2">
{{ annonce._source.titre }}
</p>
<p class="m-0">{{ 'Réf' }}: {{ annonce._source.reference }}</p>
<div class="d-flex mt-2 text--bold">
<div class="d-flex me-2">
{{ annonce._source.ville }}
</div>
</div>
<div>
<input type="checkbox" name="checkbox[]" id="checkbox_pdf" value="{{annonce._id}}" multiple/>
</div>
</div>
{% endfor %}
</div>
<input type="submit" id="pdf_submit" value="Create PDF" name="submit_pdf" class="btn btn-primary">
</form>
view of the pagination :
// I tried to add a onclick : onclick='document.forms["name"].submit(); return false;' on each pagination link combined with the save of the value in session with my controller but doesn't work
<div class="col d-flex justify-content-between align-items-center">
<div class="d-flex">
{% if page > 0 %}
<a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':0, 'type':'frontoffice'}) }}" data-target="pagination-target">
«
</a>
<a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':page-1, 'type':'frontoffice'}) }}" data-target="pagination-target">
{{ 'Précédent' }}
</a>
{% else %}
<a href="#" disabled="disabled" >
{{ 'Précédent' }}
</a>
{% endif %}
</div>
<div>
<ul class="list-unstyled pagination m-0">
{% for i in (page+1)..(page+4) %}
{% if i <= numberOfMaxPage %}
{% if i == (page+1) %}
<li>
<a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':(i-1), 'type':'frontoffice'}) }}" data-target="pagination-target">
{{ i }}
</a>
</li>
{% else %}
<li>
<a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':(i-1), 'type':'frontoffice'}) }}" data-target="pagination-target">
{{ i }}
</a>
</li>
{% endif %}
{% endif %}
{% endfor %}
</ul>
</div>
<div class="d-flex">
{% if page < (numberOfMaxPage-1) %}
<a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':page+1, 'type':'frontoffice'}) }}" data-target="pagination-target">
{{ 'Suivant' }}
</a>
<a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':numberOfMaxPage-1, 'type':'frontoffice'}) }}" data-target="pagination-target">
»
</a>
{% endif %}
</div>
</div>
JS of the pagination :
$( document ).ready(function() {
$(document).on('click', 'a.pagination',function(e) {
e.preventDefault();
$.ajax({
url: $(this).data('uri'),
}).done(function(html) {
$('#pagination-target').html(html);
$('html,body').animate({scrollTop: $('#pagination-target').offset().top - 80}, 200);
var $scrollable = document.getElementById('pagination-target');
$scrollable.scrollIntoView();
});
});
});
In my controller I render my view like this :
public function search(Request $request, ?SecteurGeographique $secteurGeographique, AnnonceRepository $annonceRepository): Response
{
$selectId = $request->get('checkbox');
$selected = $annonceRepository->findById($selectId);
// I tried to add this code to save my values
if (isset($selectId))
{
$session = new Session();
$session->set('checkbox',$selectId);
}else{
echo 'false';
$session = new Session();
$session->clear();
}
return $this->render('front/annonce/list.html.twig', array(
'annonces' => $results['hits']['hits'],
'total' => $results['hits']['total']['value'],
'website' => $website,
'page' => $request->query->getInt('page')
));
}
It is better to do a save in session my php or in ajax ?
thanks you in advance
Actually, if I understood correctly your code, you don't really need to use session.
I assume that, when you submit the form, then you will need to post all the checkbox value at once to generate your PDF.
If that is try, you should only store the list of the checkboxes directly via Javascript and be sure to send everything when you submit your form.
In this theory, there could be you HTML main page :
<form>
<div class="row" >
{% for annonce in annonces %}
<div class="col-12 col-md-6 col-lg-4">
<p class="text text--blue text--bold m-0 text--medium mt-2">{{ annonce._source.titre }}</p>
<p class="m-0">{{ 'Réf' }}: {{ annonce._source.reference }}</p>
<div class="d-flex mt-2 text--bold">
<div class="d-flex me-2">
{{ annonce._source.ville }}
</div>
</div>
<p>
<input type="checkbox" name="checkbox[]" class="checkboxPDF" value="{{annonce._id}}"/>
</div>
{% endfor %}
</div>
<div id="savedCheckboxes" class="d-none"></div>
<input type="submit" id="pdf_submit" value="Create PDF" name="submit_pdf" class="btn btn-primary">
</form>
Here, you can see that I added the invisible div #savedCheckboxes. That will allow us to save all the checkboxes when you change your pages. I also corrected a little bit your HTML, but nothing major.
Then you should update your pagination javascript :
$(document).ready(function() {
$(document).on('click', 'a.pagination',function(e) {
e.preventDefault();
// Save all the selected checkboxes by moving them to #savedCheckboxes
$('.checkboxPDF:checked').appendTo($('#savedCheckboxes'))
// Do your pagination like you did
$.ajax({
url: $(this).data('uri'),
}).done(function(html) {
$('#pagination-target').html(html);
// If the user come to a previous page, verify if he did selected a checkbox
$('#pagination-target .checkboxPDF').each(function(i, element) {
// If the checkbox already exists in the #savedCheckboxes, then select this checkBox & remove it from #savedCheckboxes
var savedCheckbox = $('#savedCheckboxes .checkboxPDF[value="'+element.val()+'"]')
if(savedCheckbox.length > 0) {
element.click() // Select this checkbox
savedCheckbox.remove() // Remove it from the hidden selection
}
})
$('html,body').animate({scrollTop: $('#pagination-target').offset().top - 80}, 200);
var $scrollable = document.getElementById('pagination-target');
$scrollable.scrollIntoView();
});
});
});
And the magic is done ... When you will submit your form, you will always receive ALL the list of the selected Checkbox, even those that are not displayed anymore because of your pagination.
I'm trying to deactivate existing_name fields based on values that selected on action field
I'm using crispy and rendering option for action field from models.py
action = models.CharField(max_length=30,
choices=[('add', 'Add'), ('delete', 'Delete'), ('modify', 'Modify'),
('rename', 'Rename')])
I had check all same question on Stackoverfllow and all suggested to deactivate it by script with changes happen action fields
{% extends "KPI_App/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<form action="" method="post" autocomplete="off" >
{% csrf_token %}
<div class="row">
<div class="col-md-4 id='1'">{{form.action|as_crispy_field}}</div>
</div>
<div class="row">
<div class="row id='existing_name' " >{{form.existing_name|as_crispy_field}}</div>
<div class="row">
<div class="col-md-8">
<button type="submit" class="btn btn-success btn-block btn-lg"><i class="fas fa-database"></i> Submit</button>
</div>
<div class="col-md-4">
<a href="{% url 'KPI_list' %}" class="btn btn-secondary btn-block btn-lg">
<i class="fas fa-stream"></i> Back to List
</a>
</div>
</div>
</form>
{% endblock content %}
<script>
$(document).ready(function(){
$("select[name='action']").on('change',function(){
if($(this).val()=='1'){
$("input[name='existing_name']").prop("disabled",false);
}else{
$("input[name='existing_name']").prop("disabled",true);
}
});
});
</script>
I can't assign id for these class and use it it script
Assuming your form input ids are the django default: id_action and id_existing_name.
function toggleAction() {
if ($('#id_action :selected').text() == "Modify") {
$('#id_existing_name').prop('disabled',false)
}
else {
$('#id_existing_name').prop('disabled',true)
}
}
$(document).on('click change', '#id_action', function() {
toggleAction()
})
$(document).ready(function() {
toggleAction();
});
In the code below the DOM does not load at all and events are not fired when I include the $("body").on() functions. When I try the functions within the .ready() individually they still do not work, even the "alert("Hi!")" does not work. But when I take out all the functions and leave only the alert("Hi!") the alert gets fired, is there any known reason why including either or all of the $("body").on() functions stops the DOM from loading?
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready( function(){
alert("Hi!");
$("body").on("click", ".sorter", function(event){
$('.row.replace').empty();
$('.row.replace').append("<br><br><br><br><p align='center'><img id='theImg' src='/media/loading1.gif'/></p><br><br><br><br><br><br><br><br>");
var sort = $(this).attr("name");
var filter = $('.select').find(":selected").attr("name");
//var csrftoken = getCookie('csrftoken');
$.ajax({
type: "POST",
url: "/filter_home/" + filter + "/" + sort + "/",
data: {'name': 'me', 'csrfmiddlewaretoken': '{% csrf_token %}'},
success : function(data) {
$('.row.replace').html(data);
//$('.row.replace').html("{% load endless %}{% paginate 6 dishes %}" + data + "<h2 align='center'>{% show_pages %}")
},
error : function(xhr,errmsg,err) {
alert(err);
}
}); //end ajax
return false;
}); //end onclick
$("body").on("change", ".select", function(event){
$('.row.replace').empty();
$('.row.replace').append("<br><br><br><br><p align='center'><img id='theImg' src='/media/loading1.gif'/></p><br><br><br><br><br><br><br><br>");
var filter = $(this).find(":selected").attr("name");
//var csrftoken = getCookie('csrftoken');
$.ajax({
type: "POST",
url: "/filter_home/" + filter + "/" + "TrendingNow" + "/",
data: {'name': 'me', 'csrfmiddlewaretoken': '{% csrf_token %}'},
success : function(data) {
$('.row.replace').html(data);
//$('.row.replace').html("{% load endless %}{% paginate 6 dishes %}" + data + "<h2 align='center'>{% show_pages %}")
},
error : function(xhr,errmsg,err) {
alert(err);
}
}); //end ajax
return false;
}); //end onchange
$("body").on("click", ".upvote", function(event){
var x = $(this).attr("name");
//var csrftoken = getCookie('csrftoken');
$.ajax({
type: "POST",
url: "/upvote/" + x + "/",
data: {'name': 'me', 'csrfmiddlewaretoken': '{% csrf_token %}'},
dataType: "json",
success : function(json) {
var y = "vote-count" + x;
$('i[class= "' + y + '"]').text(json.vote_count);
//flip button
$('.flip'+x).find('.card').toggleClass('flipped');
},
error : function(xhr,errmsg,err) {
alert("oops, something went wrong! Please try again.");
}
}); //and ajax
return false;
}); //end onclick
}); //end on ready
</script>
Accompanying HTML code
<div class="widewrapper weak-highlight">
<div class="container content">
<h3 align="center"> Choose Box: </h3>
<select class="select">
<option value="All" name="All">All</option>
<!--<option value="People You Follow" name="PeopleYouFollow">People You Follow</option>-->
{% for box in boxes %}
<option value="{{ box.name }}" name="{{ box.name }}">{{ box.name }}</option>
{% endfor %}
</select>
<div class="row">
<div class="span12">
<div class="showroom-controls">
<div class="links">
Trending Now
<i class="verticalSeparator"></i>
<a class="sorter" name="RecentlyAdded">Recently Added</a>
<i class="verticalSeparator"></i>
All Time Most Upvoted
</div>
</div>
<div class="row replace" id="entries">
{% for dish, liked in dishes %}
<div class="showroom-item span3">
<div class="thumbnail">
<img class="food_pic" src="/media/{{ dish.image }}" alt="Portfolio Image">
<div class="span3c">
<b> {{ dish.name }} </b>
</div>
<div class="span3d">
posted by <b> {{ dish.creator }}</b>
</div>
<div class="span3c">
<div class="btn-group">
<div class="flip flip{{ dish.id }}">
<div class="card">
{% if liked %}
<div class="face front">
<button type="button" class="btn btn-grove-one upvote" id="upvote" name="{{ dish.id }}">Upvoted <i class="glyphicons thumbs_up"><i></i></i><i class="vote-count{{ dish.id }}">{{ dish.other_votes }}</i></a></button>
</div>
<div class="face back">
<button type="button" class="btn btn-grove-two upvote" id="upvote" name="{{ dish.id }}">Upvote <i class="glyphicons thumbs_up"><i></i></i><i class="vote-count{{ dish.id }}">{{ dish.other_votes }} </i></a></button>
</div>
{% else %}
<div class="face front">
<button type="button" class="btn btn-grove-two upvote" id="upvote" name="{{ dish.id }}">Upvote <i class="glyphicons thumbs_up"><i></i></i><i class="vote-count{{ dish.id }}">{{ dish.other_votes }} </i></a></button>
</div>
<div class="face back">
<button type="button" class="btn btn-grove-one upvote" id="upvote" name="{{ dish.id }}">Upvoted <i class="glyphicons thumbs_up"><i></i></i><i class="vote-count{{ dish.id }}">{{ dish.other_votes }}</i></a></button>
</div>
{% endif %}
</div>
</div>
</div>
<div class="btn-group">
<button type="button" class="btn btn-grove-two"><i class="glyphicons comments"><i></i></i><fb:comments-count href=http://www.feastbox.com/dish/{{ dish.id }}/></fb:comments-count></button>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
<div class="clearfix">
</div>
</div>
</div>
</div>
</div>