Bootstrap one modal with different buttons - javascript

I'm trying to create a modal with varying content that would lead to different URLs depending on item's ID.
I came up with this code for modal:
{% for user_expense_category in user_expense_categories %}
<div class="row mb-1 d-flex justify-content-between">
<div>{{ user_expense_category.name }}</div><div>{% if user_expense_category.monthly_limit %}
Limit: {{ user_expense_category.monthly_limit }}{% endif %}</div>
<div><button type="button" class="btn btn-dark" data-toggle="modal" data-target="#editExpense" data-id="{{ user_expense_category.id }}"
data-name="{{ user_expense_category.name }}" {% if user_expense_category.monthly_limit %}data-monthly_limit="{{ user_expense_category.monthly_limit }}"{% endif %}> Edytuj </button></div>
</div>
{% endfor %}
<div class="modal fade" id="editExpense" tabindex="-1" aria-labelledby="#editExpense" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editExpenseLabel">Edytuj kategori&eogon; wydatku</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="/settings/id:/editExpCat" method="post">
<table>
<tr>
<td><label for="name">Nazwa:</label></td>
<td><input name="name" id="name" class="form-control m-1" required></td>
</tr>
<tr>
<td><label for="monthly_limit">Limit miesi&eogon;czny:</label></td>
<td><input name="monthly_limit" type="number" id="monthly_limit" class="form-control m-1" step="0.01" min="0.01"></td>
</tr>
</table>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Anuluj</button>
<button type="submit" class="btn btn-primary">Zapisz</button>
</div>
</div>
</div>
</div>
And for JS:
$('#editIncome').on('show.bs.modal', function (event) {
const button = $(event.relatedTarget)
const id = button.data('id')
const name = button.data('name')
const monthly_limit = button.data('monthly_limit')
const modal = $(this)
modal.find('.modal-body form').action('/settings/' + id + '/editIncCat')
modal.find('.modal-body input name="name"').val(name)
modal.find('.modal-body input name="monthly_limit"').val(monthly_limit)
})
Apparantely there is no such function as modal.find('').action so my question is: How do I insert different action for the form in the modal depending on the item's ID?
I've tried code above and got an error:
Uncaught TypeError: modal.find(...).action is not a function
at HTMLDivElement.<anonymous> (app.js:52:34)
at HTMLDivElement.dispatch (jquery-3.6.0.min.js:2:43064)
at v.handle (jquery-3.6.0.min.js:2:41048)
at Object.trigger (jquery-3.6.0.min.js:2:71515)
at HTMLDivElement.<anonymous> (jquery-3.6.0.min.js:2:72110)
at Function.each (jquery-3.6.0.min.js:2:3003)
at S.fn.init.each (jquery-3.6.0.min.js:2:1481)
at S.fn.init.trigger (jquery-3.6.0.min.js:2:72086)
at e.show (modal.js:115:22)
at HTMLDivElement.<anonymous> (modal.js:570:14)

Related

Modal Form Connected to SQLite3

I have the following code that is purposed to display a table of data and allow the user to add a new row by clicking a +New button, which opens a modal with the correct form, and then the user hits submit and the new row saves in the table.
I am struggling to convert the modal from static, fake data to the data coming from my SQLite3 database. Anytime I try and add my fields (e.g. { stakeholder.employee }) into the modal I get an error:
Error:
Invalid block tag on line 123: 'stakeholder.id'. Did you forget to register or load this tag?
Table of existing data with a button on top to add a new row:
<div class="col-md-12">
<button type="button" class="btn btn-primary badge-pill float-right" style="font-size: 14px; width:80px;" data-toggle="modal" data-target="#new">+ New</button>
</div>
<table class="table table-hover" style="width:90% ">
<thead>
<tr style="font-family: Graphik Black; font-size: 14px">
<th scope="col">#</th>
<th scope="col">Employee</th>
<th scope="col">Stakeholder Group</th>
<th scope="col">Quadrant</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
{% for stakeholder in stakeholder_list %}
<tr style="font-family: Graphik;font-size: 12px">
<td>{{ stakeholder.id }}</td>
<td style="font-size: 15px">{{ stakeholder.employee }}</li></td>
<td>{{ stakeholder.stakeholder_group }}</td>
<td>{{ stakeholder.stakeholder_quadrant }}</td>
<td>{{ stakeholder.description }}</td>
<td><button type="button" class="btn btn-danger btn-sm badge-pill" style="font-size: 11px; width:60px" data-toggle="modal" data-target="#new">Edit</button></td>
</tr>
{% endfor %}
</tbody>
</table>
And a Modal that I am trying to convert into a form:
<div class="modal fade" id="new" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Customer Form</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{% csrf_token %}
{{ form.non_field_errors }}
<form>
{% for field in form %}
{% endfor %}
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Doe, John">
<small id="emailHelp" class="form-text" style="color:red"><i>*Required Field</i></small>
</div>
<br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
models.py
class Stakeholder(models.Model):
employee = models.CharField(max_length=200)
stakeholder_group = models.CharField(max_length=200)
description = models.CharField(max_length=200)
stakeholder_quadrant = models.CharField(max_length=200)
def __str__(self):
return self.stakeholder
The error being raised:
Invalid block tag on line 123: 'stakeholder.id'. Did you forget to register or load this tag?
In my experience can be raised in cases such as the following:
An unclosed tag within the document
Malformed mustache variable {% stakeholder.id %} maybe?
Entangled tags?
So I recommend you sift through your template for such cases. My bet is thats where your problem is coming from.

My Delete modalForm always delete the first object in the dataModel?(Django)

I made a modal using bootstrap to delete user entries in a list view so i had to iterate with a for loop in the template so it always deletes the first object, also it never closes. How I can make the button of each entry unique that it deletes this object only.
here's the modal :
{% for obj in patients %}
<div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="modalDelete"
aria-hidden="true">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Delete patient!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this patient?</p>
</div>
<div class="modal-footer">
<form method="POST" action="{% url 'patients:patient_delete' obj.pk %}">
{% csrf_token %}
<input class="btn btn-danger" value="Yes" type="submit" >
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
{% endfor %}
and here's my triggering button :
<button type ="button" class ="btn btn-danger" data-toggle="modal" data-target="#modalDelete" >Delete</button>
You give all your modal forms the same id. You should disambiguate, for example by adding the primary key to your id, like:
{% for obj in patients %}
<div class="modal fade" id="modalDelete{{ obj.pk }}" tabindex="-1" role="dialog" aria-labelledby="modalDelete"
aria-hidden="true">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Delete patient!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this patient?</p>
</div>
<div class="modal-footer">
<form method="POST" action="{% url 'patients:patient_delete' obj.pk %}">
{% csrf_token %}
<input class="btn btn-danger" value="Yes" type="submit" >
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
{% endfor %}
and as triggering button:
<button type ="button" class ="btn btn-danger" data-toggle="modal" data-target="#modalDelete{{ obj.pk }}">Delete</button>

e.preventDefault jquery not working with multiple forms and buttons

I have a problem with a JS script I'm working with :
I have a page that handles various operations using AJAX, multiple forms with different IDs are inside the page and in my script I use e.preventDefault at the beginning of ever button's on submit event, so that it doesn't redirect to form's action attribute but instead let me use AJAX and retrieve informations in the console, the problem is that not all the preventDefault work in the file, here it is :
// Various buttons to show/hide things, here e.PreventDefault works
$('#AddCategoryLinkToggle').on('click', function(e) {
e.preventDefault();
$('#addACategoryBlock').fadeIn();
});
$('#AddBrandLinkToggle').on('click', function(e) {
e.preventDefault();
$('#addABrandBlock').fadeIn();
});
$('#CloseAddCategory').on('click', function(e) {
e.preventDefault();
$('#addACategoryBlock').fadeOut();
});
$('#CloseAddBrand').on('click', function(e) {
e.preventDefault();
$('#addABrandBlock').fadeOut();
});
// end various buttons section
// FIRST AJAX SCRIPT, this e.PreventDefault works
$('#AddCategoryForm').on('submit', function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
var postData = $(this).serializeArray();
var Actionurl = $(this).attr('action');
$.post(Actionurl, postData)
.fail(function(data) {
$('#AddCategoryError').fadeIn();
$('#AddCategoryForm').fadeOut();
})
.done(function(data) {
//console.log(data);
$('#AddCategoryForm').fadeOut();
$('#AddCategorySuccess').fadeIn();
setTimeout(function(){ location.reload(); }, 2000);
});
// TODO
});
// 2nd AJAX script, it works since it's the same as the first one
$('#AddBrandForm').on('submit', function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
var postData = $(this).serializeArray();
var Actionurl = $(this).attr('action');
$.post(Actionurl, postData)
.fail(function(data) {
$('#AddBrandError').fadeIn();
$('#AddBrandForm').fadeOut();
})
.done(function(data) {
//console.log(data);
$('#AddBrandForm').fadeOut();
$('#AddBrandSuccess').fadeIn();
setTimeout(function(){ location.reload(); }, 2000);
});
// TODO
});
// 3rd AJAX script , DOESN'T WORK
$('#DeleteModal').on('submit', function(e) {
// Stop the browser from submitting the form.
var target = $(this);
var postData = $(this).serializeArray();
var Actionurl = $(this).attr('action');
var category_name = postData[1]['value'];
e.preventDefault();
$.post(Actionurl, postData)
.fail(function(data) {
//$('#'+ category_name +'ConfirmDelete').removeClass("disabled");
//$('#'+ category_name +'PostAlertError').fadeIn('fast');
})
.done(function(data) {
//$('#'+ category_name +'ConfirmDelete').addClass("disabled");
//$('#'+ category_name +'PostAlertSuccess').fadeIn('fast');
alert("Fatto!");
});
$('.closeModal').click(function(e) {
$('#'+ category_name +'ConfirmDelete').removeClass("disabled");
$('.postAlert').hide();
location.reload();
});
// TODO
});
// 4th AJAX script, DOESN'T WORK - same as previous
$('#EditCategoryForm').on('submit', function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
var postData = $(this).serializeArray();
var Actionurl = $(this).attr('action');
var category_name = postData[1]['value'];
$.post(Actionurl, postData)
.fail(function(data) {
$('#'+ category_name +'EditCategoryError').fadeIn();
$('#EditCategoryForm').fadeOut();
$('#'+ category_name +'ConfirmCategoryEdit').addClass("disabled");
})
.done(function(data) {
console.log(data);
$('#EditCategoryForm').fadeOut();
$('#'+ category_name +'EditCategorySuccess').fadeIn();
$('#'+ category_name +'ConfirmCategoryEdit').addClass("disabled");
});
// Reset Modals and Cards
$('#'+ category_name +'CloseEditCategoryModal').click(function(e) {
$('#'+ category_name +'ConfirmCategoryEdit').removeClass("disabled");
$('.postAlert').hide();
setTimeout(function(){ location.reload(); }, 2000);
});
// TODO
});
Comments in it says it all, I don't know what I've done wrong and I've spent quite a while trying to figure it out, I hope you can help me.
EDIT : The HTML as requested, a bit long :
<div class="container">
<div id="addACategoryBlock">
<div class="row">
<div class="col-lg-12"><h4>Add a new category to the site</h4></div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="row">
<div class="col-lg-12">
<div id="AddCategorySuccess" class="alert alert-success alert-dismissible postAlert">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i> Category Added successfully!</h4>
</div>
<div id="AddCategoryError" class="alert alert-warning alert-dismissible postAlert">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-warning"></i> There's been an error</h4>
</div>
</div>
</div>
<form id="AddCategoryForm" method="POST" action="{{ path_for('auth.categories.add') }}">
<div class="form-group">
<div class="col-lg-6">
<input name ="category_name" class="form-control" id="category_name" placeholder="Name" type="text" required>
<input name="slug" class="form-control" id="slug" placeholder="Slug" type="text" required>
</div>
</div>
<div class="form-group">
<div class="col-lg-6">
<label>Select a brand to connect it with this new category</label>
<select multiple="multiple" class="form-control" name="brands[]" size="{{ countNum }}">
{% for brand in brands %}
<option value="{{ brand.brand_id }}">{{ brand.brand_name|capitalize }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-6 text-center">
<button type="submit" class="btn btn-primary">Add category</button>
</div>
<div class="col-lg-6 text-center">
<button id="CloseAddCategory" type="button" class="btn btn-primary">Close</button>
{{ csrf.field | raw }}
</div>
</div>
</form>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<h1>Categories</h1>
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Categories in the site</h3>
<small class="pull-right">or <a id="AddCategoryLinkToggle" href="#">add a new category</a></small>
</div>
<!-- /.box-header -->
<div class="box-body">
<table class="table table-bordered table-striped text-center">
<tbody><tr>
<th>#</th>
<th>Name</th>
<th>Slug</th>
<th>Brands inside this category</th>
<th>Action</th>
</tr>
{% for category in categories %}
<!-- Modal -->
<div class="modal fade" id="{{ category.slug }}Delete" tabindex="-1" role="dialog" aria-labelledby="{{ category.slug }}DeleteLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="{{ category.slug }}DeleteLabel">Delete {{ category.category_name|capitalize }}</h4>
</div>
<div class="modal-body">
<h2>Are you sure you want to delete {{ category.category_name|capitalize }} ?</h2>
<h4>This action is permanent.</h4>
<div id="{{ category.category_name|lower }}PostAlertSuccess" class="alert alert-success alert-dismissible postAlert">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i> Record deleted successfully!</h4>
</div>
<div id="{{ category.category_name|lower }}PostAlertError" class="alert alert-warning alert-dismissible postAlert">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-warning"></i> Alert!</h4>
Warning alert preview. This alert is dismissable.
</div>
</div>
<div class="modal-footer">
<form id="DeleteModal" class="DeleteModal" method="POST" action="{{ path_for('auth.categories.delete') }}">
<input name="category_id" type="hidden" value="{{ category.category_id }}">
<input class="category_name" name="category_name" type="hidden" value="{{ category.category_name|lower }}">
<button type="button" class="btn btn-default closeModal" data-dismiss="modal">Close</button>
<button id="{{ category.category_name|lower }}ConfirmDelete" name="confirmDelete" type="submit" class="btn btn-primary confirmDelete">Confirm</button>
{{ csrf.field | raw }}
</form>
</div>
</div>
</div>
</div>
<div class="modal fade" id="{{ category.slug }}Edit" tabindex="-1" role="dialog" aria-labelledby="{{ category.slug }}EditLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="{{ category.slug }}EditLabel">Edit {{ category.category_name|capitalize }}</h4>
</div>
<form id="EditCategoryForm" method="POST" action="{{ path_for('auth.categories.edit') }}">
<div class="modal-body">
<div id="{{ category.category_name|lower }}EditCategorySuccess" class="alert alert-success alert-dismissible postAlert">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i> Record updated successfully!</h4>
</div>
<div id="{{ category.category_name|lower }}EditCategoryError" class="alert alert-warning alert-dismissible postAlert">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-warning"></i> Alert!</h4>
There's been an error!
</div>
<div class="form-group">
<label for="EditName">Name</label>
<input type="text" class="form-control" name="EditName" id="EditName" placeholder="Name" value="{{ category.category_name|capitalize }}">
<label for="EditSlug">Slug</label>
<input type="text" class="form-control" name="EditSlug" id="EditSLug" placeholder="Slug" value="{{ category.slug }}">
</div>
<div class="form-group">
<label>Edits brands connected with this category</label>
<select multiple="multiple" class="form-control" name="brands[]" size="{{ countNum }}">
{% for brand in brands %}
{% if brand.brand_id in correlated %}
<option selected="selected" value="{{ brand.brand_id }}">{{ brand.brand_name|capitalize }}</option>
{% else %}
<option value="{{ brand.brand_id }}">{{ brand.brand_name|capitalize }}</option>
{% endif %}
{% endfor %}
</select>
<input type="hidden" class="form-control" name="category_id" id="category_id" value="{{ category.category_id }}">
</div>
</div>
<div class="modal-footer">
<button id="{{ category.category_name }}CloseEditCategoryModal" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="{{ category.category_name }}ConfirmEditModal" type="submit" class="btn btn-primary">Save changes</button>
</div>
{{ csrf.field | raw }}
</form>
</div>
</div>
</div>
<!-- end modal -->
<tr>
<td>{{ category.category_id }}</td>
<td>{{ category.category_name|capitalize }}</td>
<td>{{ category.slug }}</td>
<td>
<ul>
{% for brand in category.brands %}
<li>{{ brand.brand_name }}</li>
{% endfor %}
</ul>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-block btn-primary" data-toggle="modal" data-target="#{{ category.slug }}Delete">Delete</button>
<button type="button" class="btn btn-block btn-primary" data-toggle="modal" data-target="#{{ category.slug }}Edit">Edit</button>
<!--Prova edit-->
</div>
</td>
</tr>
{% endfor %}
</tbody></table>
</div>
<!-- /.box-body -->
<div class="box-footer clearfix">
<!--<ul class="pagination pagination-sm no-margin pull-right">
<li>«</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>»</li>
</ul>-->
</div>
</div>
</div>
</div>
</div>
Try return false:
$('#DeleteModal').on('submit', function (e) {
// ...
return false;
});
$('#EditCategoryForm').on('submit', function (e) {
// ...
return false;
});

onclick listener working only in particular order?

I have a dynamically created table https://imgur.com/a/NDkVX on click of tick mark a modal opens https://imgur.com/a/0RI1W on click of accept the values must be inserted into database but this happens if i do it in order from top to bottom i.e from 1st person then next..if I start from random point like I click the accept button of 4th person in the starting then null values are inserted..please help me?
<!-- html code for tick button and accept -->
<td>
<button type="button" class="btn btn-default btn-sm" data-toggle="modal" data-target="#{{pl.id}}_1"><i class="fa fa-check" aria-hidden="true" style="color:green"></i></button>
<!-- Modal -->
<div class="modal fade" id= "{{pl.id}}_1" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Do You want to accept <b>{pl.employee.emp_name|title }} </b> leave?</h4>
</div>
<form action={% url 'm_manage:accept' %} method="POST">
{% csrf_token %}
<div class="modal-body">
<p><input type="checkbox" name="email" id="email" > Notify Via Email<br></p>
<p><label for="message">Message </label>
<textarea rows="3" name="message" id="message" class="form-control input-md"></textarea></p>
</div>
<div class="modal-footer" id="{{pl.id}}">
<button type="button" class="btn btn-success" id="accept_{{pl.id}}" data-dismiss="modal">Accept</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</td>
<!--my jQuery call---->
$(document).on('click','[id^="accept_"]', function(e){
e.preventDefault();
var v_id=$(this).closest('div').attr('id');
// tried msg
var msg=$('#message').val();
// tried getElementbyId
// var msg_1=document.getElementById("message").value;
var check=$('#email').is(':checked');
console.log(msg);
// console.log(msg_1);
console.log(check);
console.log(v_id);
Identifier in HTML must be unique, duplicate identifiers creates invalid HTML.
You can use class selector to target elements and DOM traversal method to target desired elements.
Additionally use data-* custom attribute to store arbitrary data which can be fetched using .data() method.
Modify you HTML as
<!-- Modal -->
<div class="modal fade" id= "{{pl.id}}_1" role="dialog" data-id="{{pl.id}}">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Do You want to accept <b>{pl.employee.emp_name|title }} </b> leave?</h4>
</div>
<form action={% url 'm_manage:accept' %} method="POST">
{% csrf_token %}
<div class="modal-body">
<p><input type="checkbox" name="email" class="email" > Notify Via Email<br></p>
<p><label for="message">Message </label>
<textarea rows="3" name="message" class="message" class="form-control input-md"></textarea></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success accept" data-dismiss="modal">Accept</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
Script
$(document).on('click', '.accept', function (e) {
e.preventDefault();
var modal = $(this).closest('.modal');
var v_id = modal.data('id');
var msg = modal.find('.message').val();
var check = modal.find('.email').is(':checked');
console.log(v_id, msg, check);
});

Flask and JavaScript Confirm Before Deleting

I have a problem with flask app published pythonanywhere. This is a dashboard and if I click the title of the posting, it is supposed to show details of the posting. I want to add confirm message before delete. How can I make it? Now I try to use javascript, but it doesn't work. Below are my codes.
app.py
import MySQLdb as mysql
con = mysql.connect("host", "username", "password", "database")
con.ping(True)
#app.route('/deleteschool/<int:School_Id>')
def deleteschool(School_Id):
try:
if session.get('user'):
#con = mysql.connect()
cursor = con.cursor()
query_string = "DELETE FROM school WHERE School_Id = '{School_Id}'".format(School_Id=School_Id)
cursor.execute(query_string)
#cursor.execute("DELETE from school where School_Id=%s", (School_Id))
delete=cursor.fetchall()
if len(delete) is 0:
con.commit()
return redirect('/getSchoolList')
else:
return redirect('/error')
else:
return redirect('/error')
except Exception as e:
return redirect('/error')
school_page_showpost.html
<script src="/static/js/confirm.js"></script>
{% for row in schoolpost %}
<div id="titleOutput" class="two fields">
<div class="field">
<label>TITLE</label>
<textarea id="ckeditor1" class="cleditor" disabled="yes" readonly="yes" rows="1">{{row[1]}}</textarea></div></div>
<div id="contentsOutput" class="field">
<h6></h6>
<label>CONTENTS</label>
<textarea id="ckeditor2" class="cleditor" disabled="yes" readonly="yes" rows="10" cols="80">{{row[2]}}
</textarea>
<script>
var editor2=CKEDITOR.replace( 'ckeditor2' );
</script>
</div>
</div>
<div class="extra content">
<div class="right floated author">
<span class="right floated time">{{row[4]}} </span>
<span class="category">School board </span>
<span class="writer">
{{row[3]}}</span>
</div>
</div>
</div>
<br><br>
<ul class="actions pagination">
<li><a onclick="javascript : window.location = '/editschool/{{row[0]}}' " class="ui button">EDIT</a></li>
<li><button id="confirmDeleteSchool" type="submit" name="confirmDeleteSchool" class="ui button">DELETE</button></li>
<li><a href="/school" class="ui button" >LIST</a></li>
</ul>
{% endfor %}
confirm.js
$(function(){
$('#confirmDeleteSchool').click(function(){
var confirm = confirm("Are you sure?");
if (confirm == true) {
$.ajax({
url: '/delteschool/{{row[0]}}',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
} else {
}
});
});
If I click delete button, it is supposed to load confirm.js file and execute. But it does nothing. Please help.
An alternative approach for a similar task:
I implemented a confirmation step before deleting post through modal by using only HTML and jinja.
{% block body %}
<h1>Dashboard <small> Welcome {{session.username}} </small></h1>
<a class="btn btn-success" href="/add_article">Add Article</a>
<hr>
<table class="table table-striped">
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Date</th>
<th></th>
<th></th>
</tr>
{% for article in articles %}
<tr>
<td>{{article.id}}</td>
<td>{{article.title}}</td>
<td>{{article.author}}</td>
<td>{{article.create_date}}</td>
<td> Edit </td>
<td>
<!-- Button trigger modal -->
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#exampleModalCenter{{article.id}}">
Delete
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter{{article.id}}">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle{{article.id}}">Deleting Post Permanently</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h3>{{article.title}}??</h3>
<p>Are you sure?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<form action="{{url_for('delete_article', id=article.id)}}" method="post">
<input type="submit" value="Delete" class="btn btn-danger">
</form>
</div>
</div>
</div>
</div>
</td>
</tr>
{% endfor %}
</table>
{% endblock %}
Including a js file in Flask works differently:
`<script type="text/javascript" src="{{ url_for('static', filename='js/confirm.js') }}"></script>`
With this you should be able to load the JS

Categories