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>
Related
As I am implementing AJAX, I would like this whole <div> to show up as a consequence of clicking the button in the script below :
<div class="col-12" id="deleteVote">
<div class="row mb-2" >
<div class="col-12">
{% for vote in proposal.votes %}
{% if app.user == vote.user %}
<a href="{{ path('vote_delete',{'slug' : slug, 'proposal' : proposal.id, 'vote' : vote.id}) }}" class="btn btn-light ml-1 btn-sm deleteVote" data-toggle="deleteConfirmation">
<i class="bi bi-trash"></i> {{ 'vote-delete' | trans }}
</a>
{% endif %}
{% endfor %}
</div>
</div>
</div>
Here is the script, I don't really know why the .show is not working :
<script>
$(document).on('click', '.votedFullAgreement', function (){
$.ajax({
url: '{{ path('vote_add', {'slug' : slug, 'proposal' : proposal.id, 'userVote' : 'votedFullAgreement', 'user' : app.user.id }) }}',
type: 'POST',
dataType: 'html',
success: function (){
$('#deleteVote').show();
},
error: function (resultat, statut, erreur) {
}
});
return false;
});
</script>
Btw the script is probably not optimised at all but it's my first one and it's working and sending data...
Thank you !
EDIT 2 :
I don't understand why this if/else doesn't work. When there's a vote, the if works, the button is there when we come back/reload the page, but when there is no vote yet, the .show(); doesn't activate the else which is in display:none.
Is it because as soon as I vote, the if becomes true? (and .show(); needs something previously hidden to display but can't find any...)
{# Standard loop #}
{% if proposal.votedByUser(app.user) %}
<div class="col-12">
<div class="row mb-2">
<div class="col-12">
{% for vote in proposal.votes %}
{% if app.user == vote.user %}
<a href="{{ path('vote_delete',{'slug' : slug, 'proposal' : proposal.id, 'vote' : vote.id}) }}" class="btn btn-light ml-1 btn-sm" data-toggle="deleteConfirmation">
<i class="bi bi-trash"></i> {{ 'vote-delete' | trans }}
</a>
{% endfor %}
</div>
</div>
</div>
{% else %}
{# AJAX loop #}
<div class="col-12">
<div class="row mb-2">
<div class="col-12">
{% for vote in proposal.votes %}
{% if app.user == vote.user %}
{# ID deleteVote here, which has display:none in the CSS #}
<a href="{{ path('vote_delete',{'slug' : slug, 'proposal' : proposal.id, 'vote' : vote.id}) }}" id="deleteVote" class="btn btn-light ml-1 btn-sm" data-toggle="deleteConfirmation">
<i class="bi bi-trash"></i> {{ 'vote-delete' | trans }}
</a>
{% endif %}
{% endfor %}
</div>
</div>
</div>
{% endif %}
If I split both loops, the AJAX one works only when there is already a vote registered (and the button of the standard loop is already there)
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 have a post in a community and i have implemented the like button in django + ajax but i notice that when i do like a post it increments all the post's likes.how can i solve it ?
here is my template:
{% for post in posts %}
<div class="w3-container w3-card w3-white w3-round">
<a target="_blank" href="{{ post.author.profile.avatar.url }}">
<img src="{{ post.author.profile.avatar.url }}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px"></a>
<h4>
<a href ='{% url 'profile' post.author.pk %}'>{{ post.author.profile.prenom|title }} {{ post.author.profile.nom|title }}</a>
</h4>
<span class="w3-opacity">{{ post.created|date:"d-m-Y H:i" }}</span>
<br>
<hr class="w3-clear">
<p>
{{ post.contenu }}</p>
<button type="button" class="btn btn-default btn-sm">
{{ post.comment_set.count }} </span>
</button>
{% if request.user in post.liked.all %}
<button type="button" class="btn btn-default btn-sm">
<span class='like_count'>{{ post.liked.count }} </span><a name="{{ post.id }}" style="color: blue;" class="likin" id="co"><span class="glyphicon glyphicon-heart"></span> j'aime</a>
</button>
{% else %}
<button type="button" class="btn btn-default btn-sm">
<span class='like_count'>{{ post.liked.count }} </span><a name="{{ post.id }}" style="color: black;" class="likin" id="co"><span class="glyphicon glyphicon-heart"></span> j'aime</a>
</button>
{% endif %}
{% if request.user == post.author %}
<button type="button" class="btn btn-default btn-sm">
</span>
</button>
{% endif %}
<br>
<br>
</div>
<br>
{% empty %}
<span class='w3-opacity'>Aucun post dans cette communaute</span>
<br>
<br>
{% endfor %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// AJAX CALL
$('.likin').click(function(){
$.ajax({
type: "POST",
url: "{% url 'like_community' %}",
data: {'content_id': $(this).attr('name'),'operation':'like_submit','csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response) {
selector = document.getElementsByName(response.content_id);
if(response.liked==true){
$(selector).css("color","blue");
$('.like_count').html(response.likes_count);
}
else if(response.liked==false){
$(selector).css("color","black");
$('.like_count').html(response.likes_count);
}
}
});
})
</script>
this is my views.py with the part ajax like:
def like_community(request):
if request.method =="POST":
if request.POST.get("operation") == "like_submit" and request.is_ajax():
content_id=request.POST.get("content_id",None)
content=get_object_or_404(Post,pk=content_id)
if content.liked.filter(id=request.user.id): #already liked the content
content.liked.remove(request.user) #remove user from likes
liked=False
else:
content.liked.add(request.user)
liked=True
ctx={"likes_count":content.liked.count() ,"liked":liked,"content_id":content_id}
return HttpResponse(json.dumps(ctx), content_type='application/json')
i really need a help.i am new in ajax and i just find a tutorial online and i follow but the implementation of count_like button was not there.i will appreciate any help.Merci.
You seem to have non-unique ID of "co" - Then you use the wrong method document.getElementsByName which returns a collection of NAMED elements but you pass it response.content_id
Also you use $('#response.content_id') which will look for an element with `id="response.content_id"
Change to
$('.likin').click(function(e){
e.preventDefault; // stop the link
$liked = $(this); // the link clicked
$.ajax({
success: function(response) {
$liked.prev().html(response.likes_count); // the span before the "likin"
$liked.css("color",response.liked==true ? "blue": "black");
}
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>