Flask and JavaScript Confirm Before Deleting - javascript

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

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.

JS HTML: Get particular column value after button click

I have a table with several columns. Each row has an edit button.
If the user clicks on it, a modal view opens. The user can enter some values and send these via AJAX to my controller.
My problem is that I have no idea how to transfer to my JS function which particular edit button the user has actually clicked in the table.
In the past I had an edit button in each row:
<td><a th:href="'/edit/' + *{person.getName()}" class="btn-sm btn-success"
role="button">Edit</a></td>
But this led me to a new HTML view where the user could edit. With my new UI I want really only to go with the modal.
But since JS/AJAX has no idea about the whole table it seems to me like a totally wrong approach to me. Moreover I am pretty new to JS/AJAX
Currently I call the JS function like this:
<button type="button" class="btn btn-primary"
id="subscribe-email-form" onclick="updateModal()">Save
</button>
What can solve my Problem?:
If I could just give a parameter to updateModal it would work but since I call the modal view with id="myModal" by the edit button with data-target="#myModal" I cannot transfer any id.
Here is my JS and what I want is to find the correct parameter for the field oldID
Thank you a lot in advance!
function updateModal() {
var newValues = {};
newValues["newName"] = $("#newName").val();
newValues["newAge"] = $("#newAge").val();
newValues["newID"] = $("#newID").val();
var oldID = "???";
$.ajax({
type: "POST",
contentType: "application/json",
url: "/api/edit/oldID",
data: JSON.stringify(newValues),
dataType: 'json',
timeout: 100000,
success: function (data) {
console.log("SUCCESS: ", data);
display("SUCCESS");
resultObj = data.result;
updateContent(resultObj[0].phone);
},
error: function (e) {
console.log("ERROR: ", e);
display("ERROR");
//display(2);
},
done: function (e) {
console.log("DONE");
display("DONE");
enableSearchButton(true);
}
});
}
and the relevant HTML part
<div class="container">
<br>
<h3>Overview</h3>
<br>
<div class="container" id="modal-submit">
<div class="col-12">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
<th scope="col">ID</th>
</tr>
</thead>
<tbody>
<!--/*#thymesVar id="productList" type="java.util.List"*/-->
<tr id="person" th:each="person : ${elementList}">
<td th:text="${person.getName()}" id="username"></td>
<!--/*#thymesVar id="getTradableBTC" type="java.lang.Double"*/-->
<td th:text="${person.getAge()}" th:id="${person.getName()+person.getAge()}" id="age"></td>
<!--/*#thymesVar id="getTop" type="java.lang.Double"*/-->
<td th:text="${person.getId()} " th:id="${person.getName()+person.getId()}" id="userID"></td>
<td>
<div class="btn-toolbar" role="toolbar">
<!-- Button trigger modal -->
<div class="btn-group mr-2" role="group" aria-label="First group">
<button type="button" class="btn btn-outline-primary btn-sm" data-toggle="modal"
data-target="#myModal">
Edit
</button>
</div>
<div class="btn-group mr-2" role="group" aria-label="Second group">
<button type="button" class="btn btn-outline-danger btn-sm" id="delete">Delete
</button>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<button class="btn btn-primary" type="button" id="addElement">Add Element</button>
<button class="btn btn-light" type="button" id="DeleteAll">Delete all Elements</button>
</div>
</div>
<br>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Change data</h5>
<button type="button" class="close" data-dismiss="modal"
aria-label="Close"><span
aria-hidden="true">×</span></button>
</div>
<div class="row">
<div class="col-sm-6">
<div class="modal-body">
<input name="referencia" id="newName" type="text"
class="form-control"
placeholder="Enter new name">
<br>
<input name="referencia" id="newAge" type="text"
class="form-control"
placeholder="Enter new age">
<br>
<input name="referencia" id="newID" type="text"
class="form-control"
placeholder="Enter new id">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Discard
</button>
<button type="button" class="btn btn-primary"
id="subscribe-email-form" onclick="updateModal()">Save
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<br>
1st: id= must be unique so don't duplicate ids .. person1 , age1 , userID1 for the next person 1 will be 2 and so on.. you can also use class= instead of id=
2nd: If change it to classes .. on edit button click you can use
alert($(this).closest('tr').find('.userID').text());
You can then pass the userID to the modal and get it again when saveEdit
Note: This code'll work if you change id="person" to class="person" same thing with age and userID
Again and Again Don't use same id for more than one element .. delete button has duplicated id .. so you need to change it as well .. and after change id="delete" to class="delete" you can then use
$('.delete').on('click' , function(){
// do ajax things for remove then
$(this).closest('tr').remove();
});
If you append the rows dynamically you'll need to use
$(document).on( 'click' , '.delete' , function(){ /* code here */ }); // use same way with dynamically created element events

Update database value with Bootstrap Modal and Laravel 5.2

I can normally insert, update and delete data from database with Laravel 5.2. Now i want to update table data with Bootstrap Modal . My modal and Table view in same blade.
Modal:
<!-- Modal content-->
<div class="modal-content">
#foreach($dataQrDetails as $dataQr)
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Updating {{ $dataQr->winner_name }}</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" action="{{url('admin/winner/status/'.$dataQr->id)}}" method="POST" enctype="multipart/form-data" id="contactForm">
{{ csrf_field() }}
<input type="hidden" name="chance_of_win" value="Shipped">
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Text Input</label>
<div class="col-md-9">
<div class="input-icon">
<i class="fa fa-archive" aria-hidden="true"></i>
<input type="text" class="form-control" placeholder="{{ trans('common.enter') }}" name="status_text" value="{{ $dataQr->status_text}}"></div>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green" id="submitContact" form="contactForm">{{ trans('common.submit') }}</button>
</div>
</div>
</div>
</form>
</div>
#endforeach
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
tbody:
<tbody>
#foreach($dataQrDetails as $dataQr)
<tr>
<td> {{ $dataQr->winner_name }} </td>
<td> {{ $dataQr->username }} </td>
<td> {{ $dataQr->winner_gender }} </td>
<td> {{ $dataQr->mobile_no }} </td>
<td> {{ $dataQr->ship_address }} </td>
<td> {{ $dataQr->product_name }} </td>
<td> {{ $dataQr->product_stat }} </td>
<td> {{ $dataQr->created_at }} </td>
<td> <button type="button" class="btn btn-info btn-xs" data-toggle="modal" data-target="#myModal" data-winner="{{ json_encode($dataQr) }}">Open Modal</button>
</tr>
#endforeach
</tbody>
Controller:
public function statusUpdate(Request $request, $id)
{
$id = $request->input("id");
$winner = Winner::find($id);
if ($winner->product_stat == "Shipped") {
echo "Its Already Shipped!";
}else{
$winner->product_stat = "Shipped";
$winner->status_text = $request->get('status_text');
$winner->save();
$request->session()->flash('alert-info', 'Product Status Updated!');
return Redirect::to('admin/winner/detail');
}
}
Routes:
Route::post('/winner/status/{id}', ['as' => 'winner.status', 'uses' => 'WinnerController#statusUpdate']);
Now if i click on edit button of one row then its open Bootstrap modal with all value. But it should be the clicked value. Again if i fill up modal and click on submit button then its not updating into database. Its just redirect ../public/admin/winner/status/18 url with MethodNotAllowedHttpException error. How can i do that? Thanks in advance.
I make this work by using little bit JavaScript. Hope it will help who want to update data with Bootstrap Modal and Laravel Framework. Retrieve data from database with js and show it in modal with id.
Modal Looks Like:
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Updating "<span class="qr_winner_name_show" style="color: #32c5d2;"></span>" Shipping Status</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" action="{{url('admin/winner/status/update')}}" method="POST" enctype="multipart/form-data" id="contactForm">
<input type='hidden' name='id' class='modal_hiddenid' value='1'>
{{ csrf_field() }}
<input type="hidden" name="chance_of_win" value="Shipped">
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Text Input</label>
<div class="col-md-9">
<div class="input-icon">
<i class="fa fa-archive" aria-hidden="true"></i>
<input type="text" class="form-control modal_status_inp" placeholder="{{ trans('common.enter') }}" name="status_text" value=""></div>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green" id="submitContact" form="contactForm">{{ trans('common.submit') }}</button>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
Passing id when i click on button with data-id="{{ $dataQr->id }}" again if you need to pass another value then you can pass like this way.
tbody:
<tbody>
#foreach($dataQrDetails as $dataQr)
<tr id="qrd_{{$dataQr->id}}">
<td class="qr_winner_name"> {{ $dataQr->winner_name }} </td>
<td> {{ $dataQr->username }} </td>
<td> {{ $dataQr->winner_gender }} </td>
<td> {{ $dataQr->mobile_no }} </td>
<td> {{ $dataQr->ship_address }} </td>
<td> {{ $dataQr->product_name }} </td>
<td> {{ $dataQr->product_stat }} </td>
<td> {{ $dataQr->created_at }} </td>
<td> <button type="button" class="btn btn-info btn-xs openModal" data-id="{{ $dataQr->id }}" data-status-text="{{ $dataQr->status_text }}" data-toggle="modal" data-target="#myModal">Delier</button></td>
</tr>
#endforeach
</tbody>
JS:
$(document).ready(function(){
$(document).on('click','.openModal',function(){
var id = $(this).data('id');
$('.modal_hiddenid').val(id);
$('.modal_status_inp').val($(this).data('status-text'))
var qr_winner_name = $('#qrd_'+id+' .qr_winner_name').html();
$('.qr_winner_name_show').html(qr_winner_name);
});
})
Routes:
Route::get('/winner/status/{id}', ['as' => 'winner.status', 'uses' => 'WinnerController#editStat']);
Route::post('/winner/status/update', ['as' => 'winner.change', 'uses' => 'WinnerController#statusUpdate']);
Controller:
public function editStat($id)
{
//
$winner = Winner::findOrFail($id);
return view('winner.detail', ['id' => $id, 'winner' => $winner]);
}
public function statusUpdate(Request $request, $id=0)
{
$id = $request->input("id");
$winner = Winner::find($id);
if ($winner->product_stat == "Shipped") {
$request->session()->flash('alert-warning', 'Its has been already Shipped! Try another one.');
return Redirect::to('admin/winner/detail');
}else{
$winner->product_stat = "Shipped";
$winner->status_text = $request->get('status_text');
$winner->save();
$request->session()->flash('alert-info', 'Product Status Updated!');
return Redirect::to('admin/winner/detail');
}
}
Hope it will help some who wants to insert/update database value with Bootstrap Modal and Laravel Framework.
To update or insert into your database you need to use POST method.
Your GET method need to replace with POST method.
You have so many options to make it working.
I'will show you one:
Make a seperate GET Route e.g /winner/edit/{id}
then in your Controller function render a view which contains the modal content:
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Edit Item</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<input value="{{$model->whatever}}">
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn green" id="submitContact" form="contactForm">{{ trans('common.submit') }}</button>
</div>
</div>
</div>
Controller function
fuction edit($id) {
return view('edit_modal')->with(['model' => Model::find($id)])->render();
}
In the click function of your edit button load this view over ajax, fill the content of your modal, and show it.
There are many other way, depends on the size of your project and what functions you will also achieve.
e.g. Use a Libaray for JS Object binding (knockoutjs)
Total simple but resource eating way:
Render a seperate modal for each Model and open only the corresponding one on click.
#foreach($dataQrDetails as $dataQr)
<div class="modal fade" id="{{$dataQR->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">Updating {{ $dataQr->winner_name }}</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" action="{{url('admin/winner/status/'.$dataQr->id)}}" method="POST" enctype="multipart/form-data" id="contactForm">
{{ csrf_field() }}
<input type="hidden" name="chance_of_win" value="Shipped">
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Text Input</label>
<div class="col-md-9">
<div class="input-icon">
<i class="fa fa-archive" aria-hidden="true"></i>
<input type="text" class="form-control" placeholder="{{ trans('common.enter') }}" name="status_text" value="{{ $dataQr->status_text}}"></div>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green" id="submitContact" form="contactForm">{{ trans('common.submit') }}</button>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#endforeach
<td> <button type="button" class="btn btn-info btn-xs" onclick:$('#'+{{$dataQR->id}}).modal('show')>Open Modal</button>

Laravel 5.4: Delete Modal Not Obtaining Object

So I have a table of people, with each column containing certain values. At the end of each row, I have a "Delete" button. When that button is pressed, a modal pops up to confirm if you want to proceed with deleting that person. Clicking the "Delete" button again should delete the person and display a success message for it.
With the modal, I'm trying to make sure not only that a user needs to accept the action before proceeding, but also making sure that only the specific person in question is deleted. However, when I try to clarify the request it only contains the CSRF token that I'm passing through. Even when I try to more deliberately inject the targeted person into the modal the person isn't being sent through.
The important snippets of my code, for reference:
#foreach($people as $person)
<tr id="row{{ $loop->iteration }}">
<td id="first_name_row{{ $loop->iteration }}">{{ $person->first_name }}</td>
<td id="last_name_row{{ $loop->iteration }}">{{ $person->last_name }}</td>
<td id="email_row{{ $loop->iteration }}">{{ $person->email }}</td>
<td>
<input type="button" id="delete_button_row{{ $loop->iteration }}" class="btn btn-btn-submit delete" value="Delete" onclick="delete_modal('{{ $loop->iteration }}', {{ $person }})">
</td>
</tr>
#endforeach
..........
<!-- Modal -->
<div class="modal fade" id="DeleteModal" role="dialog">
<div class="modal-dialog">
<form class="form-horizontal style-form" id="model-form" data-toggle="validator" role="form" method="post" action="/employer/delete-person">
<!-- Modal content-->
{{ csrf_field() }}
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Delete This Person</h4>
</div>
<div class="modal-body">
<p>Are you sure you would like to do that?</p>
<input id="delete_ex">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" id="modal-execute" class="btn btn-btn-submit">Delete</button>
</div>
</div>
</form>
</div>
</div>
......
<script>
function delete_modal(num, person){
$('#delete_button_row' + num).attr("data-toggle" , "modal");
$('#delete_button_row' + num).attr("data-target", "#DeleteModal");
$('#delete_ex').val(person);
}
.......
</script>

jquery, django-deleteview: delete table row records

I am trying to open up a twitter bootstrap model for the confirmation of deleting the records while constructing a simple CRUD application.
this is where the confirmation message appears in a bootstrap modal form with delete button at the end to let us delete the selected row.
<div class="modal fade" id="myDeleteModal" tabindex="-1" role="dialog" aria-labelledby="myEditModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only"></span></button>
<h4 class="modal-title" id="myDeleteModalLabel"></h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete {{ obj.name }}?</p>
<form action="" method="post" id="delete_form" id="form-modal-body">
<div class="modal-footer">
<button class="btn btn-danger btn-small pull-left" data-dismiss="modal">
<i class="icon-remove"></i>Cancel
</button>
<button type="button" class="btn btn-primary" id="delete_submit">Delete</button>
</div>
</form>
</div>
</div>
</div>
</div>
And this is where the records are listed with a delete action at the end of each row:
<tbody id="new-day-row">
{% for day in object_list %}
<tr class="odd">
<td id='day-{{day.id}}'>{{ day.name }}</td>
<td id='workday-{{day.id}}'>{{ day.work_day }}</td>
<td class="td-actions">
<a class="red" href="#" data-toggle="modal" data-target="#myDeleteModal">
<i class="icon-trash bigger-130"></i>
</a>
</td>
</tr>
{% endfor %}
</tbody>
A very simple deleteView:
class DayDeleteView(DeleteView):
model = Day
def get_success_url(self):
return reverse('day_home')
I was hoping to get an answer to trigger the delete action in jquery. I had so far tried to bind the .remove() function on the click event of the button but was not successfull whatsoever and truly not worth it to post here. I Would be very thankfull for suggestions and answers.
I'd just use on:
html:
<div class="modal-footer" id="{{obj.id}}">
jquery:
$('#delete_submit').on('click', function() {
var id = $('.modal-footer').attr('id');
$.ajax({
url: "your/delete/handler",
type: "POST",
data: { id : id },
});

Categories