cannot access Hidden field value with jQuery - javascript

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()

Related

Issue with Blueimp Jquery FileUpload For Individual Uploads

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 %}

Add prices to total with checkbox select Django

I am building a feature to add different services to the checkout in my Django template, but I don't know how to add the total price when selecting checkboxes.
I put a change event on each checkbox and to this and when I check one it is supposed to add the service and its price in the card.
The card :
<div class="col-4">
<h4 class="d-flex justify-content-between align-items-center mb-3">
<span class="text-muted">Votre commande</span>
</h4>
<ul class="list-group mb-3" id="panier">
<li class="list-group-item d-flex justify-content-between lh-condensed">
<div>
<h6 class="my-0">{{annonce.titre_logement}}</h6>
<small class="text-muted">{{annonce.categorie_logement}}</small>
</div>
<span class="text-muted">{{annonce.loyer_tc}} €</span>
</li>
</ul>
<li class="list-group-item d-flex justify-content-between">
<span>Total (€)</span>
<strong><span id="total"></span> €</strong>
</li>
</div>
The checkboxes and the script :
{% for categorie in categorie_service %}
{% for service in services %}
{% if service.categorie.value == categorie_service.nom %}
<div class="form-check">
<input class="form-check-input" type="checkbox" name="service" value="{{ service.nom }}" id="service{{ service.id }}">
<label class="form-check-label" for="service{{ service.id }}">
{{ service.nom }}
</label>
</div>
<script>
$(document).ready(function() {
$('#service{{ service.id }}').change(function() {
if(this.checked) {
var returnVal = "<li class='list-group-item d-flex justify-content-between lh-condensed'>\
<div>\
<h6 class='my-0'>{{service.nom}}</h6>\
</div>\
<span class='text-muted'>{{service.price}}€</span>\
</li>"
$('#panier').append(returnVal);
var total
total = {{annonce.loyer_tc}}
total = total + parseInt({{service.price}} || 0,10);
totalDiv = document.getElementById("total");
totalDiv.innerHTML = total;
}
});
});
</script>
{% endif %}
{% endfor %}
{% endfor %}
and here is my view if needed :
def detail_annonce(request, pk):
myObject = Annonce.objects.get(id=pk)
image = ImageLogement.objects.all()
categorie_service = myObject.categorie_service.all()
services = Services.objects.all()
context = {'annonce': myObject, 'myImages': image, 'categorie_service': categorie_service, 'services':services}
return render(request, 'annonce/search/annonce_result.html', context)

JQuery/AJAX call function seems to run only once and JQuery selector on AJAX result only yields the inner html

I am new to programming and this is also my first question on this platform. I have tried implementing applicable solutions I could find here for similar questions raised but is still stuck. Should you believe that a previously answered question might answer mine, please share the link to such answer. Also please correct me should you find that I have broken some guidelines on how to properly ask questions on this platform.
Now, on to the actual issues.
The following are the relevant sections (please, let me know if I have missed something that might be relevant). The issues are stated on my comments on modals.js.
modals.js
$(document).ready(function(){
$('#frmAddProduct').on('submit', function aj (event) {
event.preventDefault();
$.ajax({
cache: false,
type : 'POST',
url : '/products/new',
data : $('#frmAddProduct').serialize(),
datatype: 'html'
})
.done(function process (data) {
/* The modal has to be shown unless the user clicks on 'close'*/
$('#modalAdd').modal('show');
let err = $(data).find(".invalid-feedback").html();
if (err){
/* replace the contents of the modal with section from
ajax result to show validation messages*/
let cont = $(data).find("#targetModalContent").html();
$('#targetModalContent').html(cont);
/* Once the code above executes, clicking the submit button again
terminates the whole process.
Maybe this section requires a loop or recursion? But this part
is already on the "on submit" listener, right?*/
}
else {
/* Show success flash message on the modal instead of the original
below nav location */
console.log(data);
let msg = $(data).closest("#targetFlash").html();
/* using the .find doesn't work and results in msg=undefined.
I don't understand why that is the case, I tried using .parent
but it also did not work, or maybe I was using the .parent improperly.
I also tried $($(data).closest("#targetFlash")).parent().html but
it too didn't worked.
Why is it returning only the message and not the whole node
with the enclosing div?
*/
$('#frmAddProduct fieldset>div:first').prepend(msg);
}
});
});
});
products.html
{% extends "tblayout.html" %}
<!-- Main Content -->
{% block thead %}
{% endblock %}
{% block tbody %}
{% endblock %}
{% block tfoot %}
{% endblock %}
{% block maincont %}
<!-- ModalAdd -->
<div class="modal fade" id="modalAdd" tabindex="-1" role="dialog" aria-labelledby="modalAddTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content" id="targetModalContent">
<div class="modal-header">
<h5 class="modal-title" id="modalAddLongTitle">Add {{ legend }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST" action="" id="frmAddProduct">
{{ formAdd.csrf_token }}
<div class="modal-body">
<div class="container-fluid">
<fieldset class="form-group">
<div class="form-group row">
{{ formAdd.productSubCategory.label(class="col-form-label col-sm-5") }}
{% if formAdd.productSubCategory.errors %}
{{ formAdd.productSubCategory(class="form-control col-sm-7 is-invalid") }}
<div class="invalid-feedback">
{% for error in formAdd.productSubCategory.errors %}
<span class="col-sm-7 offset-5">{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ formAdd.productSubCategory(class="form-control col-sm-7") }}
{% endif %}
</div>
<div class="form-group row">
{{ formAdd.brand.label(class="col-form-label col-sm-5") }}
{% if formAdd.brand.errors %}
{{ formAdd.brand(class="form-control col-sm-7 is-invalid") }}
<div class="invalid-feedback">
{% for error in formAdd.brand.errors %}
<span class="col-sm-7 offset-5">{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ formAdd.brand(class="form-control col-sm-7") }}
{% endif %}
</div>
<div class="form-group row">
{{ formAdd.description.label(class="col-form-label col-sm-5") }}
{% if formAdd.description.errors %}
{{ formAdd.description(class="form-control col-sm-7 is-invalid") }}
<div class="invalid-feedback">
{% for error in formAdd.description.errors %}
<span class="col-sm-7 offset-5">{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ formAdd.description(class="form-control col-sm-7") }}
{% endif %}
</div>
</fieldset>
</div>
</div>
<div class="modal-footer">
<div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
<div>
{{ formAdd.submit(class="btn btn-primary") }}
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
<!-- Optional Body scipt loaded after the main content has loaded -->
{% block bodyscript %}
<script src="../static/js/modals.js"></script>
{% endblock %}
AJAX result on Issue #1
<!-- ModalAdd -->
<div class="modal fade" id="modalAdd" tabindex="-1" role="dialog" aria-labelledby="modalAddTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content" id="targetModalContent">
<div class="modal-header">
<h5 class="modal-title" id="modalAddLongTitle">Add Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST" action="" id="frmAddProduct">
<input id="csrf_token" name="csrf_token" type="hidden" value="ImNlZDc1Njc0MTY4NTg5NTNhNDg0NWEyNGYyZjYzZmIyYmFmMTZhZmQi.YAamUA.WGi03w__AklqccdIQgK_pWG5oJg">
<div class="modal-body">
<div class="container-fluid">
<fieldset class="form-group">
<div class="form-group row">
<label class="col-form-label col-sm-5" for="productSubCategory">Product Sub-Category</label>
<select class="form-control col-sm-7 is-invalid" id="productSubCategory" name="productSubCategory" required><option selected value="1">ProductCategory1, ProductSubCategory1</option><option value="2">ProductCategory1, ProductSubCategory2</option><option value="3">ProductCategory2, ProductSubCategory3</option></select>
<div class="invalid-feedback">
<span class="col-sm-7 offset-5">Product combination is already enrolled.</span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-5" for="brand">Brand</label>
<select class="form-control col-sm-7 is-invalid" id="brand" name="brand" required><option selected value="1">Brand1</option><option value="2">Brand2</option><option value="3">Brand3</option></select>
<div class="invalid-feedback">
<span class="col-sm-7 offset-5">Product combination is already enrolled.</span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-5" for="description">Product Description</label>
<input class="form-control col-sm-7 is-invalid" id="description" name="description" placeholder="New Product" required type="text" value="45">
<div class="invalid-feedback">
<span class="col-sm-7 offset-5">Product combination is already enrolled.</span>
</div>
</div>
</fieldset>
</div>
</div>
<div class="modal-footer">
<div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
<div>
<input class="btn btn-primary" id="submit" name="submit" type="submit" value="Add Product">
</div>
</div>
</form>
</div>
</div>
</div>
AJAX result on Issue #2 (I have copied only the target div since the rest of the html data is just the same, this is right below the nav)
<div class="alert alert-success" id="targetFlash">
Product 45 has been added!
</div>
main.routes.py
#main.route("/products", methods=['GET', 'POST'])
#login_required
def products():
formAdd = frmAddProduct()
formMod = frmModProduct()
q = sess.query(Product.id.label("PId"),
Product.description.label("PDesc"),
Product.isactive.label("PIsactive"),
ProductSubCategory.id.label("PSCid"),
ProductCategory.description.label("PCDesc"),
ProductSubCategory.description.label("PSCDesc"),
Brand.id.label("BId"), Brand.name.label("BName"))\
.select_from(Product)\
.join(ProductSubCategory)\
.join(ProductCategory)\
.join(Brand)\
.all()
page = request.args.get('page', 1, type=int)
qp = paginate.Page(q, items_per_page=5, page=page)
data = sqlaq2dict(qp)
npage = qp.pager(url= url_for('main.products') + "?page=$page",
link_attr=dict({'class':'btn btn-outline-primary mb-4'}),
curpage_attr=dict({'class':'btn btn-primary mb-4'}),
dotdot_attr=dict())
pagenav = Markup(npage)
return render_template("products.html", title='Products', legend='Product',
data=data, pagenav=pagenav, formAdd=formAdd, formMod=formMod)
#main.route("/products/new", methods=['POST'])
#login_required
def addProduct():
formAdd = frmAddProduct()
if formAdd.validate_on_submit():
p = Product()
p.productSubCategory_id = formAdd.productSubCategory.data
p.brand_id = formAdd.brand.data
p.description = formAdd.description.data
p.isactive = formAdd.isactive.data
syncNext('management', 'Product', 'id') # Ensures right ID for Postgres
sess.add(p)
sess.commit()
flash(
f'Product {formAdd.description.data} has been added!', 'success')
# return jsonify({"status" : "success"}) #Cannot have multiple returns
return redirect(url_for('main.products'))
return render_template("products.html", title='Products', legend='Product',
formAdd=formAdd)
forms.py
class frmAddProduct(FlaskForm):
# productSubCategories = sess.query(ProductSubCategory.id,\
# ProductSubCategory.fullDesc)\
# .filter(ProductSubCategory.isactive==True)\
# .all()
psc = sess.query(ProductCategory.description.label("PCDesc"),
ProductSubCategory.id.label("PSCId"),
ProductSubCategory.description.label("PSCDesc"))\
.join(ProductSubCategory)\
.all()
pscDict = sqlaq2dict(psc) #Converts the resulting tuple to dict
productSubCategories = []
for r in pscDict:
i = (r['PSCId'], r['PCDesc'] + ', ' + r['PSCDesc'])
productSubCategories.append(i)
productSubCategory = SelectField('Product Sub-Category',
choices=productSubCategories,
coerce=int,
validators=[InputRequired()])
brands = sess.query(Brand.id, Brand.name)\
.filter(Brand.isactive == True)\
.all()
brand = SelectField('Brand', choices=brands, coerce=int,
validators=[InputRequired()])
description = StringField('Product Description', validators=[
DataRequired()], render_kw={"placeholder": "New Product"})
isactive = BooleanField('Status', default=True)
submit = SubmitField('Add Product')
#---------------------------------------------Should be composite Key
def validate_productSubCategory(self, productSubCategory):
user = sess.query(Product)\
.filter(Product.productSubCategory_id == self.productSubCategory.data,
Product.brand_id == self.brand.data, Product.description ==
self.description.data)\
.first()
if user:
raise ValidationError('Product combination is already enrolled.')
def validate_brand(self, brand):
user = sess.query(Product)\
.filter(Product.productSubCategory_id == self.productSubCategory.data,
Product.brand_id == self.brand.data, Product.description ==
self.description.data)\
.first()
if user:
raise ValidationError('Product combination is already enrolled.')
def validate_description(self, description):
user = sess.query(Product)\
.filter(Product.productSubCategory_id == self.productSubCategory.data,
Product.brand_id == self.brand.data, Product.description ==
self.description.data)\
.first()
if user:
raise ValidationError('Product combination is already enrolled.')

Select a specific button in Javascript/AJAX

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>

DOM not loading

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>

Categories