Code is getting executed even when hitting cancel button (ajax) - javascript

Okay so I have a function "deactivate" which passes in 3 parameters to it.
<a href="#myModal" onclick="deactivate('{{ $user->getRoleName() }}', '{{ $user->getFullName() }}', {{ $user->id }}); return false;" role="button" data-toggle="modal" class="btn btn-danger btn-small delete">
<i class="btn-icon-only"></i>
Deactivate User
</a>
Here is my function:
function deactivate(title, name, id) {
$('#modal-user-role').html(title);
$('#modal-user').html(name);
$('#confirm').click(function() {
$.ajax({
url: '/user/' + id + '/',
type: 'PUT',
success: function (data) {
$('#alerts').html('<p class="alert alert-success">Successfully deactivated ' + title + ': ' + name + '</p>' + $('#alerts').html());
$('#r' + id).hide();
},
error: function (jqXHR, textStatus, errorThrown) {
$('#alerts').html('<p class="alert alert-error">A problem occured while deactivating ' + title + ': ' + name + '</p>' + $('#alerts').html());
$('#r' + id).hide();
}
});
});
}
Here is my HTML that goes with the function:
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close icon-remove" data-dismiss="modal" aria-hidden="true"></button>
<h3 id="myModalLabel">Deactivate User</h3>
</div>
<div class="modal-body">
<p>Are you sure you want to deactivate user <span id="modal-user-role"></span>: <span id="modal-user"></span>?</p>
<p>This action cannot be undone.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button id="confirm" data-dismiss="modal" class="btn btn-danger">Confirm Deactivation</button>
</div>
</div>
Does anyone know why my cancel button is not working? I believe it has something to do with the onclick I am using but not quite sure how to fix it.
So, basically if I click the deactivate user button and than cancel and click another user and then cancel and then click another user and than confirm the deactivation it will delete each user from the DB.
Which I do not want.
I have the button type="button" which I thought would fix it. But it is not.
Any ideas at all would be greatly appreciated.

As I mentioned in the comments, the problem is how you are registering the click handler...
since the click handler is registered within the deactivate method, every time the method is called a new handler is added - it doesn't remove the previously added handlers...
so you can try to remove the handlers using .off()
$('#confirm').off('click.deactivate').on('click.deactivate', function () {
})
Note: When using event unbinding I prefer using name spacing

Related

Flask add modal to ask before deleting. How to get working?

In my Flask APP i have a page with a link to delete:
Is inside a table each row have this id, here I am sending the ID (that normaly I use to delete):
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" id="submits" onclick="send_to_modal('{{post.id}}')">
Borrar
</button>
Here is my javascript:
function send_to_modal(id){
document.getElementById("exampleModalLabel").innerHTML = id;
};
The modal:
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> </button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" onclick="modal_a_funccion()">SI</button>
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">NO</button>
</div>
</div>
</div>
</div>
I don´t know how to send the ID to another function that is charged to delete the specified data:
This is my function that works correcty and delete the data giving the ID:
function modal_a_funccion(id){
console.log("Solicitando un report para: "+id);
//fetch('/report/' + olt_hostname).then(function(response) {
fetch('/task/report_celery/' + id).then(function(response) {
response.json().then(function(data) {
for (var x of data.ip) {
console.log("REPORT_fetch recibe (IP): " +x.ip_oob)
console.log("REPORT_fetch recibe (ESTADO): " +x.estado)
};
});
});
};
I would like to know how to to it.
What I intend to do is add a modal to ask the user for confirmation whether or not to delete. I can't find a way to pass the Id to the function that is in charge of doing the deletion. I would like to know how to do it. Thank you so much.
A possible solution (in a different way)
When user clicks on delete for a row, add a class e.g. to_delete. Then display the modal popup asking if user wants to go ahead with the delete or not.
If user says no, close the modal and remove the class again
If user says yes, call the delete function
For 3, you do something like
// Find the element that user has marked for delete
const element = document.querySelect(".to_delete")
const id = element.id;
For 2, you do something like
// Find the element that user has marked for delete and remove the delete mark
document.querySelect(".to_delete").classList.remove("to_delete")

modal iteration in foreach loop using ajax

I got a problem with foreach loop. What am i trying to do is get data (JsonResult) from action in controller. Get get songs for each album.
public JsonResult SongListByAlbum(int albumID)
{
var songs = (from song in Song.GetSongList()
join album in Album.GetAlbumList()
on song.AlbumID equals album.AlbumID
where (albumID == album.AlbumID)
select song).ToList();
return Json(songs,JsonRequestBehavior.AllowGet);
}
Then put them into view, for album get list of songs and show them as modals
There is my view:
#foreach (var item in Model.Albums){
<button id="#item.AlbumID" type="button" class="btn btn-primary myModals" data-toggle="modal" data-target="#exampleModal-#item.AlbumID">
Show
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal-#item.AlbumID" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel-#item.AlbumID" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel-#item.AlbumID">#item.AlbumName #item.Year, #item.BandName</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="parent" class="modal-body">
</div>
<div class="modal-footer">
<button id="closeModal"type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
}
And there is a script, where I get songs for each album.
<script>
$(".myModals").on("click", function () {
var Id = $(this).attr('id');
alert(Id);
$.ajax({
type: "GET",
url: '#Url.RouteUrl(new{ action= "SongListByAlbum", controller="Default"})',
data: {albumID:Id},
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
for (var i in result) {
$('#parent').append('<p class="toRemove">' + result[i].SongName + '</p>');
}
},
error: function (response) {
alert('error');
}
});
});
</script>
The problem is : when i click on the first modal button everything is fine, i get what i want to. But when i click on the second one i got empty modal. Then when i click again on the first one i got data from previous click and penultimate. Image: enter image description here
To avoid multiple <div id="parent"> elements, you should probably assign the Id the same way you do for the buttons. Like <div id="parent-#item.AlbumID">. Then in your ajax call reference the correct div. $('#parent-' + Id).
Not sure if that is your only probably, but might get you closer.

Pass a variable from a function to another in jQuery

I'm a newbie in Javascript world, and I searched a lot for a similar question but never worked for me.
So I'm working with a Bootstrap modal, I have 3 buttons with different names that opens a modal window.
When I close the modal window I want an alert that show me the name of the button I've clicked.
For example, if I click on the button "Email Ted", when I close the modal the alert will say "You haven't sended the message to Ted".
I get the names from the attribute data-name="" in every button.
I also tried to insert the first function in a global variable, but didn't worked; so the code below is an idea to what I want to do.
$(document).ready(function() {
$("#exampleModal").on('show.bs.modal', function(e) {
var button = $(e.relatedTarget);
var recipient = button.data('name');
var modal = $(this);
modal.find('.modal-title').text('New message to ' + recipient);
return String(recipient);
});
$('#exampleModal').on('hidden.bs.modal', function(recipient) {
alert('The message will not be sended to ' + recipient);
});
});
Thanks!
I made a working demo out of what I understand of your question.
Please have a look and ask for what you need to be explained.
$(document).ready(function() {
$("#open").on("click",function(){
$("#exampleModal").modal("show");
});
var recipient="";
$("#exampleModal").on('show.bs.modal', function(e) {
recipient = $("#open").data('name');
var modal = $(this);
modal.find('.modal-title').text('New message to ' + recipient);
return String(recipient);
});
$('#exampleModal').on('hidden.bs.modal', function() {
alert('The message will not be sended to ' + recipient);
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<div class="modal" tabindex="-1" role="dialog" id="exampleModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal" data-name="TEST Name">Close</button>
</div>
</div>
</div>
</div>
<button id="open" data-name="John Doh">Open modal</button>
First of all it is important to mention that your snippet is not just general JavaScript, but the way Twitter Bootstrap works. There are no native shown and hidden events.
So you have custom events here. Btw. referring to the bootstrap reference, it should be shown.bs.modal (recognize the missing 'n' in your code) or maybe I am wrong and they made some changes.
You could safe the button name in a variable like so:
$(document).ready(function() {
var recipient = null;
$("#exampleModal").on('shown.bs.modal', function(e) {
var button = $(e.relatedTarget);
var modal = $(this);
recipient = button.data('name');
modal.find('.modal-title').text('New message to ' + recipient);
});
$('#exampleModal').on('hidden.bs.modal', function(recipient) {
if (recipient) {
alert('The message will not be sended to ' + recipient);
recipient = null; // important to reset this var for a second trigger
}
});
});

how re-use bootstrap modal dialog with multiple links

I am trying to re-use a bootstrap modal with this jsFiddle found http://jsfiddle.net/jhfrench/qv5u5/51/. The problem I am having is I have to refresh the page before being able to use another link. Otherwise the url from first link selected is shown when another link is selected. Can anyone see where I am going wrong?
Below is what I have.
( I apologise if I haven't done this correctly as this is my first post )
<script> $('a[data-toggle="modal"]').on('click', function(){
// update modal header with contents of button that invoked the modal
$('#myModalLabel').html( $(this).html() );
//fixes a bootstrap bug that prevents a modal from being reused
$('#utility_body').load(
$(this).attr('href'),
function(response, status, xhr) {
if (status === 'error') {
//console.log('got here');
$('#utility_body').html('<h2>Oh boy</h2><p>Sorry, but there was an error:' + xhr.status + ' ' + xhr.statusText+ '</p>');
}
return this;
}
);
});
</script>
<div id="utility" class="modal hide fade" tabindex="-1" role="dialog" aria- labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h1 id="myModalLabel">The Right to Manage Process</h1>
</div>
<div class="modal-body" id="utility_body">
<p>One fine body…this is getting replaced with content that comes from passed-in href</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
<ul>
<li><a data-target="#utility" href="retirement-modal-content/rtm-process.html" role="button" data-toggle="modal">The Right to Manage Process</a></li>
<li><a data-target="#utility" href="retirement-modal-content/mgmt-sel-prcs.html" role="button" data-toggle="modal">The Management Selection Process</a></li>
</ul>

Pass an ID To Twitter Bootstrap Model

I am trying to pass an id to a twitter bootstrap model for a delete confirmation (basic CRUD page) and for the life of me I can't get this working. Looked at several examples still unable to get to work. I need to get the data-id to pass to the model and append the href link so that for example they confirm it takes them to the appropiate page (eg: delete.php?id=5) Any ideas would be greatly appreciated. Heres my code:
The link:
<a href="#msgDelete" data-toggle="modal" class="open-dialog btn btn-mini btn-danger" data-id="'.$row["id"].'">
The Model:
<div id="msgDelete" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Are You Sure?</h3>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this product? This action can not be reversed. <br /><br /><em>Remember if you want to just hide the product from your store you can mark it as inactive.</em></p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<a href="delete.php?id=" class="btn btn-danger" id="clink" >Delete Product</a>
</div>
The JavaScript:
<script type="text/javascript">
$(document).on("click", ".open-dialog", function () {
var productId = $(this).data('id');
console.log(productId);
//$(".modal-body #clink").href( 'delete.php?id=' + productId );
$("#clink").attr("href", "delete.php?idd=" + productId);
// As pointed out in comments,
// it is superfluous to have to manually call the modal.
// $('#addBookDialog').modal('show');
});
</script>
Look like your code has misprint.
$("#clink").attr("href", "delete.php?idd=" + productId);
-----^
Should be
$("#clink").attr("href", "delete.php?id=" + productId);
At least http://jsfiddle.net/egX3W/ shows that you href changes as you want.
in your code
<a href="#msgDelete" data-toggle="modal" class="open-dialog btn btn-mini btn-danger" data-id="'.$row["id"].'">
change it to
<a data-href="delete.php?id=<?php=productId?>" data-toggle="modal" class="open-dialog btn btn-mini btn-danger" data-id="'.$row["id"].'">
so, it will be automatically pass to your javascript... and you won't need to pass it in script...
change your script to this
$(document).on("click", ".open-dialog", function () {
var productId = $(this).data('id');
console.log(productId);
});

Categories

Resources