Bootstrap Modal in Django application with Ajax - javascript

I have little problem in my Django application. I am tring to use modal from bootstrap 4 and ajax to create new object. Here below you see code that I used. When user click the button I dont see modal window but background became grey. What I did wrong? Why I dont see modal? Is my ajax correct?
detail.html:
<!-- BUTTON TO TRIGGER THE ACTION -->
<button class="add-group-task" data-toggle="modal" data-target="#add-group-task-modal" data-url="{% url 'project:group_task_add' project_code=project.code %}">{% trans 'Create' %}</button>
<table class="table table-bordered" id="group-tasks-table">
<!-- TABLE CONTENT-->
</table>
<!--MODAL-->
<div class="modal fade" id="add-group-task-modal" tabindex="-1" role="dialog" aria-labelledby="add-group-task-modal-title" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
</div>
</div>
</div>
urls.py:
url(r'^(?P<project_code>[0-9a-f-]+)/add_new_group_task/$', group_task_add, name='group_task_add'),
view.py:
def group_task_add(request, project_code):
data = dict()
project = get_object_or_404(Project, pk=project_code)
if request.method == 'POST':
form = GroupTaskAddForm(request.POST)
if form.is_valid():
group_task = form.save(commit=False)
group_task.project = project
group_task.save()
data['form_is_valid'] = True
group_tasks = GroupTask.objects.filter(project=project_code)
data['html_group_tasks'] = render_to_string('project/project_detail.html', {'group_tasks': group_tasks})
else:
data['form_is_valid'] = False
else:
form = GroupTaskAddForm()
context = {'form': form}
data['html_group_task_add_form'] = render_to_string('project/group_task_add.html', context, request=request)
return JsonResponse(data)
javascript:
$(function () {
/* Functions */
var loadForm = function () {
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#add-group-task-modal").modal("show");
},
success: function (data) {
$("#add-group-task-modal .modal-content").html(data.html_form);
}
});
};
var saveForm = function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#group-tasks-table tbody").html(data.html_group_tasks);
$("#add-group-task-modal").modal("hide");
}
else {
$("#add-group-task-modal .modal-content").html(data.html_group_task_add_form);
}
}
});
return false;
};
// Create book
$(".add-group-task").click(loadForm);
$("#add-group-task-modal").on("submit", ".js-group-task-add-form", saveForm);
});
group_task_add.html:
<form method="post" action="{% url 'project:group_task_add' project_code=project.code %}" class="js-group-task-add-form">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title" id="addGroupTaskModalLabel">{% trans 'Create a new group task' %}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="formGroupTaskInput">{% trans 'Name' %}</label>
{{ form.name }}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">{% trans 'Close' %}</button>
<button type="submit" class="btn btn-primary">{% trans 'Create' %}</button>
</div>
</form>
ERROR:

try with following html and js code combination:
<!-- BUTTON TO TRIGGER THE ACTION -->
<button ... onclick="modalHandler()">{% trans 'Create' %}</button>
// js code
function modalHandler(){
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#add-group-task-modal").modal("show");
},
success: function (data) {
$("#add-group-task-modal .modal-content").html(data.html_form);
}
});
};

Related

Laravel How to reset modal ajax data values upon closing the modal

I am currently working on populating a user's searching for available appointments by selecting a date, start time and end time. I am trying to populate them onto a modal which is currently working. However I realise that whenever I close the modal and search for the new timeslots, the previous data populated on the modal will still be there.
I have tried doing function when I close the modal, the modal data will be cleared.
Below are my html codes for the modal:
<div class="modal fade" id="myModalNewAppointment">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Select Appointment</h4>
</div>
<!-- Modal body -->
<div class="modal-body">
{{-- <form id="test" action="" method="post"> --}}
<div class="form-group">
<label for="modal">Select a Timeslot</label>
<div class="spacer"></div>
<div class="timeslots-section">
<div class="timeslots text-center">
</div> <!-- end timeslots -->
</div>
</div>
{{-- </form> --}}
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="new_appt_cfm_btn" data-loading-text="<i class='fa fa-spinner fa-spin'></i> saving..">Confirm</button>
<button type="button" class="btn btn-outline-primary" id="close_btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Below is my ajax method to retrieve the timeslots:
$("#find_appointment_btn").click(function(event){
event.preventDefault();
let select_date = $('#select_date').val();
let start_time = $('#start_time').val();
let end_time = $('#end_time').val();
let data = { select_date: select_date, start_time: start_time, end_time: end_time };
$.ajax({
type:"POST",
url: "{{ route('assistant.newappts.get') }}",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
'Content-Type': 'application/json'
},
data: JSON.stringify(data),
dataType: "json",
success:function(data){
console.log(data);
if(data == ""){
alert("Clinic is close!");
return;
}
else if(data != ""){
$('#myModalNewAppointment').modal({backdrop: 'static', keyboard: false});
data.forEach(function(dt) {
// do something with `item`
// $(".timeslots").append(dt);
$('.timeslots').append('<input type="checkbox" class="timeslotchk" name="timeslot" value="'+ dt +'"/>' + dt );
});
}
},
error: function(error) {
console.log(error);
}
});
});
Below is the method I have tried to reset the data populated on my modal:
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').reset();
});
When you call the ajax request on the success you have appended the data in model "timeslots" division so its obvious that data will be still there on the hiding model try to empty the timeslots, try below code hope it work for you and make sure that method trigger on closing of model
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').find(".timeslots").empty();
});

Show json data in bootstrap modal

Hello Im new to ajax and json and never used modals before. I need to show data which I have already taken into the console. I need to show the data on the console in a modal.
I need to show each specific details of each employee details when I click the view request button. The console is showing the correct details.
javascript
<script>
$(function(){
var BASE_URL = "http://localhost/employeemgt/index.php/";
$('#pedingLeaveRequest').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var current_leave_id = button.data('id');
var modal = $(this);
modal.find('input[name="current_leave_id"]').val(current_leave_id);
});
//approve button
$('#approvebtn').click(function(){
var id = $('input[name="current_leave_id"]').val();
$.post(BASE_URL + 'admin/AdminDashboardController/approveLeave',
{'id': id},
function(result){
console.log(result);
if(result.error){
alert('try again');
}else{
alert('Leave has been approved!');
}
});
});
//disapprove button
$('#declinebtn').click(function(){
var id = $('input[name="current_leave_id"]').val();
$.post(BASE_URL + 'admin/AdminDashboardController/disapproveLeave',
{'id': id},
function(result){
console.log(result);
if(result.error){
alert('try again');
}else{
alert('Leave has been disapproved!');
}
});
});
});
$("#showleave").on('click','button',function(event){
var BASE_URL = "http://localhost/employeemgt/index.php/";
var leave_id = $(this).val();
var response;
$.ajax({
type: 'POST',
dataType: "JSON",
data:{leave_id:leave_id},
url: BASE_URL + 'admin/AdminDashboardController/viewRequest',
success:function(data){
console.log(data);
$('#pendingLeaveRequest #leave_details').html(data);
$('#pendingLeaveRequest').modal('show');
},
error:function(error){
alert(error);
}});
});
</script>
view
<div id="showleave">
<h4 class="mb-4">Pending Requests</h4>
<?php
foreach ($leave as $row) {
if($row->status != "1")
{
echo '
<ul class="list-unstyled">
<li class="media border-bottom border-top py-3">
<img class="mr-3" src="http://via.placeholder.com/64x64" alt="Generic placeholder image">
<div class="media-body">
<h5 class="mt-0 mb-1">'.$row->user_name.'</h5>
<p class="mb-0 mt-0">'.$row->leave_start.' to '.$row->leave_end.'</p>
<p class="mt-0">'.$row->leave_type.'</p>
<button type="button" class="detailButton" href="<?php echo $id; ?>" data-id="'.$row->id.'" data-name="'.$row->user_name.'" data-target="#pendingLeaveRequest" data-toggle="modal" value="'.$row->id.'">View Request</button>
</div>
</li>
</ul>
';
}
}
?>
</div>
modal
<!-- Modal -->
<div class="modal fade" id="pendingLeaveRequest" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Leave Request</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="leave_details" >
<p>
</p>
</div>
<div class="modal-footer">
<input type="hidden" name="current_leave_id" id="current_leave_id" value="" />
<button type="button" id="declinebtn" class="btn btn-secondary" data-dismiss="modal">Decline</button>
<button type="button" id="approvebtn" class="btn btn-primary">Approve</button>
</div>
</div>
</div>
</div>
controller
public function viewRequest()
{
$leave_id = $this->input->post('leave_id');
$data = $this->Admin_Model->viewRequest($leave_id);
echo json_encode($data);
}
Use below code in your ViewRequest function, remove my previous codes.
$("#showleave").on('click','button',function(event){
var BASE_URL = "http://localhost/employeemgt/index.php/";
var leave_id = $(this).val();
var response;
$.ajax({
type: 'POST',
dataType: "JSON",
data:{leave_id:leave_id},
url: BASE_URL + 'admin/AdminDashboardController/viewRequest',
success:function(data){
console.log(data);
$('#pendingLeaveRequest #leave_details').html(data);
$('#pendingLeaveRequest').modal('show');
},
error:function(error){
alert(error);
}});
});

Javascript methods stop working after writing another method in the same script tag

I have written a code on codeigniter framework for approve and disapprove leave of employees. The approval and disapproval worked fine before. But after I write another methods in the same script tag for showing the leave details of the employees the approval and disapproval stopped working.
What can I change in order to make the two buttons work. The two buttons are also inside the modal.
javascript
<script>
$(function(){
var BASE_URL = "http://localhost/employeemgt/index.php/";
$('#pedingLeaveRequest').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var current_leave_id = button.data('id');
var modal = $(this);
modal.find('input[name="current_leave_id"]').val(current_leave_id);
});
//approve button
$('#approvebtn').click(function(){
var id = $('input[name="current_leave_id"]').val();
$.post(BASE_URL + 'admin/AdminDashboardController/approveLeave',
{'id': id},
function(result){
console.log(result);
if(result.error){
alert('try again');
}else{
alert('Leave has been approved!');
}
});
});
//disapprove button
$('#declinebtn').click(function(){
var id = $('input[name="current_leave_id"]').val();
$.post(BASE_URL + 'admin/AdminDashboardController/disapproveLeave',
{'id': id},
function(result){
console.log(result);
if(result.error){
alert('try again');
}else{
alert('Leave has been disapproved!');
}
});
});
});
//show leave details on modal
$("#showleave").on('click','button',function(event){
var BASE_URL = "http://localhost/employeemgt/index.php/";
var leave_id = $(this).val();
$.ajax({
type: 'POST',
dataType: "JSON",
data:{leave_id:leave_id},
url: BASE_URL + 'admin/AdminDashboardController/viewRequest',
success:function(data){
console.log(data);
$('#leave_details').html(data);
$('#pendingLeaveRequest').modal('show');
},
error:function(error){
alert(error);
}});
});
</script>
view:
<div id="showleave">
<h4 class="mb-4">Pending Requests</h4>
<?php
foreach ($leave as $row) {
if($row->status != "1")
{
echo '
<ul class="list-unstyled">
<li class="media border-bottom border-top py-3">
<img class="mr-3" src="http://via.placeholder.com/64x64" alt="Generic placeholder image">
<div class="media-body">
<h5 class="mt-0 mb-1">'.$row->user_name.'</h5>
<p class="mb-0 mt-0">'.$row->leave_start.' to '.$row->leave_end.'</p>
<p class="mt-0">'.$row->leave_type.'</p>
<button type="button" class="detailButton" href="<?php echo $id; ?>" data-id="'.$row->id.'" data-name="'.$row->user_name.'" data-toggle="modal" value="'.$row->id.'">View Request</button>
</div>
</li>
</ul>
';
}
}
?>
</div>
modal
<!-- Modal -->
<div class="modal fade" id="pendingLeaveRequest" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Leave Request</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="leave_details" >
<p> </p>
</div>
<div class="modal-footer">
<input type="hidden" name="current_leave_id" id="current_leave_id" value="" />
<button type="button" id="declinebtn" class="btn btn-secondary" data-dismiss="modal">Decline</button>
<button type="button" id="approvebtn" class="btn btn-primary">Approve</button>
</div>
</div>
</div>
</div>
As you are replacing the $('#pendingLeaveRequest #leave_details').html(data); with new data so the button don't work.. Try to replace it with new id....
//show leave details on modal
//$("#showleave").on('click',function(){
$('.detailButton').on('click', function(){
var BASE_URL = "http://localhost/employeemgt/index.php/";
var leave_id = $(this).val();
$.ajax({
type: 'POST',
dataType: "JSON",
data:{leave_id:leave_id},
url: BASE_URL + 'admin/AdminDashboardController/viewRequest',
success:function(data){
console.log(data);
$('#leave_details p').html(data);
$('#pendingLeaveRequest').modal('show');
},
error:function(error){
alert(error);
}});
});
let me know if it is working..

Ajax post request not passing through ID

I am currently dynamically setting data attributes on widgets which are ID's through javascript, I then get the attribute when I go to delete the widget so I can remove the widget entry from the database. I have stepped through the code in firebug and it seems to get the widgetID fine, but when I go to make an ajax post request it does not seem to append the ID for the routing value.
Here is the modal:
div class="modal fade" id="deleteWidgetModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<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="myModalLabel">Delete widget?</h4><!--add depending on which panel you have clicked-->
</div>
<div class="modal-body" id="myModalBody">
<!--Depending on which panel insert content-->
#using (Html.BeginForm("DeleteWidgetConfirmed", "Dashboard", FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
#Html.AntiForgeryToken();
<div class="form-horizontal">
Do you wish to delete this widget?
<div class="form-group">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" value="DeleteWidgetConfirmed" class="btn btn-danger btn-ok" id="delete-widget">Delete</button>
</div>
</div>
</div>
}
</div>
</div>
</div>
Here is my rendered HTML for the widget where the widgetID is set:
<div class="panel panel-default" draggable="true" data-widgetid="4">
<div class="panel-heading">
<div class="panel-body">
I then try to make a post:
$(document).ready(function () {
$('#columns').on('click', '.glyphicon.glyphicon-trash', function (event) {
var panel = this;
//get id here
//toggle the modal
$('#deleteWidgetModal').modal('show');
var widgetID = $(this).closest('.panel.panel-default').attr('data-widgetid');
document.getElementById('delete-widget').onclick = function (event) {
event.stopPropagation();
//anti forgery token
var form = $('#__AjaxAntiForgeryForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var URL = '/Dashboard/DeleteWidgetConfirmed';
console.log(widgetID + " test1");
//we make an ajax call to the controller on click
$.ajax({
url: URL,
data: {
__RequestVerificationToken: token,
id: widgetID
},
type: 'POST',
dataType: 'json',
success: function(data){
var parentElement = $(panel).closest(".col-md-4.column");
var targetElement = $(panel).closest(".panel.panel-default");
targetElement.remove();
//parentElement.addClass("expand-panel");
checkEmptyPanelContainers();
$('#deleteWidgetModal').modal('hide');
},
error: function (response) {
console.log(widgetID + " ERROR");
}
})
}
})
});
and here is my HTTP POST request which I got from the NET panel in firebug:
/Dashboard/DeleteWidgetConfirmed
and here is my controller:
// POST: DashboardModels/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteWidgetConfirmed(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DashboardModel dashboardModel = db.dashboards.Find(id);
db.dashboards.Remove(dashboardModel);
db.SaveChanges();
return new EmptyResult();
}
Here is the parameter being passed through with my response:
http://gyazo.com/696b684cc3650dd24731ad8ecdce1447

where to get the value when sending the request?

please help to solve the problem.
html:
<div class="modal fade" id="commonModal" tabindex="-1" role="dialog" aria-labelledby="commonModalLabel" 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">Close</span></button>
<h4 class="modal-title" id="commonModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default but_cancel" data-dismiss="modal">Отменить</button>
<button type="button" class="btn btn-primary but_ok" data-dismiss="modal">Ok</button>
</div>
</div>
</div>
</div>
I send ajax request as follows:
$('#commonModalLabel').text('Удалить профиль?');
$('#commonModal .modal-body').html('Возможность восстановить профиль будет доступна в течение двух недель. Для восстановления нужно отправить администратору ресурса письмо с почтового адреса, который был указан в профиле.');
$('#commonModal').modal('show');
$('#commonModal .but_ok').on('click', function(){
console.log('ok');
$.ajax({
url: "/accounts/delete_profile/",
type: 'POST',
dataType:"json",
data: {},
success: function(data) {
if(data.result == true){
$('#mySmallModalLabel').text('Профиль удалён');
$('#infoModal').modal('show');
}
}
});
});
views.py:
def delete_profile(request):
result = False
if request.method == "POST" and request.is_ajax():
username = request.POST.get('username', '')
try:
entry = User.objects.get(username=username)
entry.is_active = 0
entry.save()
except:
pass
else:
result = True
data = {
'result': result,
}
return HttpResponse(json.dumps(data), content_type='application/json')
the problem is that in the log, the following error message:
Forbidden (CSRF token missing or incorrect.):
/accounts/delete_profile/
in the case of a form, I'd send the token as follows:
{% csrf_token %}
but in my case there is no form (!). please tell me where to get the token and how to send
Put it in your AJAX request.
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
},
Sometimes it does not work in some browsers (in my case it is chrome), so you can add these to data you are sending to view:
data['csrfmiddlewaretoken'] = $.csrf_token;
$.csrf_token is a global object for me, I put token printing it to template directly:
<script type="text/javascript">
$.csrf_token = '{{ csrf_token }}';
</script>
Your problem is explained in the django docs.
Be aware, that if no form is rendered django might not send a csrf token, you'll have to use the ensure_csrf decorator

Categories

Resources