My delete page contains multiple post with delete button, when delete button is pressed bootstrap bootstrap modal opens and will ask for confirmation are you sure you want to delete post ? YES : NO
when YES button is pressed .click(function (e){....} sends AJAX request to database, if ajax return success that paticular card should be hidden
so i tried with following code
$(document).ready(function () {
$("#confirm").click(function (e) {
e.preventDefault();
var that = this;
const act = $(this).attr('data-act');
const para = $(this).attr('data-para');
const hash = $(this).attr('data-hash');
$.ajax({
url: '/include/ajax/mark_sold.php', // Call delete.php to update the database
method: 'POST',
data: {action: act, para: para, hash: hash},
cache: false,
success: function (data, status) {
$("#fetched").html(data);
$('#myModal').modal('hide');
$(that).closest('div.card').hide(); //to hide div after ajax success
},
error: function (xhr, statusText, error) {
$("#fetched").show();
$("#confirmButton").hide();
}
});
});
return false;
});
HTML
<div class="card border-0 small col-lg-3 col-md-2 col-6 mb-2 px-1">
<img class="card-img-top rounded-0" src="/upload/" alt="Card image cap">
<div class="card-body pb-0 pt-2 px-0">
<h6 class="card-title text-dark text-truncate">title</h6>
</div>
<button data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-block btn-sm modalopen" data-hash="6d8ce77d206011027297b693be999704" data-para="A4IxzuRP8ATv">delete</button>
</div>
How do i hide card after confirming in modal
The problem in your code is, that your variable "that" is not referring to the delete button, but to the confirm button of the dialog, therefore you can't use closest() function. At this point, you should use some specific identification for your card/delete button. For example:
$('button[data-hash="'+hash+'"]') .closest('div.card').hide();
Another point that I don't see in your code is the transfer of data variables (act, para, hash) to the dialog confirm button. For example your code $(this).attr('data-hash') can't reach value from the delete button because $(this) refers to the dialog confirm button. The solution to this problem is to pass a unique identifier to the dialog button.
$(".deleteBtn").on('click',function(){ //Add on click event to all delete buttons
$("#confirm").data("hash",$(this).data("hash")); //Pass hash value to dialog confirm button
});
$("#confirm").click(function (e) {
e.preventDefault();
var delBtn = $('button[data-hash="'+$(this).data("hash")+'"]'); //Get specific delete button element by passed hash value
const act = delBtn.attr('data-act'); //Get data variables from the delete button element
const para = delBtn.attr('data-para');
const hash = $(this).data("hash");
$.ajax({
url: '/include/ajax/mark_sold.php',
method: 'POST',
data: {action: act, para: para, hash: hash},
cache: false,
success: function (data, status) {
$("#fetched").html(data);
$('#myModal').modal('hide');
delBtn.closest('div.card').hide(); //Find closest .card element to the specified delete button
},
error: function (xhr, statusText, error) {
$("#fetched").show();
$("#confirmButton").hide();
}
});
});
Don't forget to add .deleteBtn class to your delete buttons.
Hope it helps.
Related
I have a Bootstrap modal dialog that I am using to populate with data when user clicks on "Edit" in a jQuery data table. There is a Cancel and Submit button on this modal.
When I open the modal and click Cancel and then select another table row and click "Edit", everything is fine; data gets populated correctly each time "Edit" is clicked. However, if I do a postback by clicking "Submit" on the modal and then click "Edit" again, modal opens and no data is there.
I am using modal's on('show.bs.modal', ...) to populate it and it never gets hit after a postback is done.
// This is called when "Edit" in data table row is clicked
function showEdit(var1, var2) {debugger
$('#hfVar1').val(var1);
$('#hfVar2').val(var2);
showEditModal();
}
function showEditModal() {debugger
$("#spnEditHeader").text("Edit Something");
$('#editModal').modal('show');
}
$(document).ready(function () {
// This populates the jQuery data table
showTable(somthing, anotherThing);
// This is executed as long there is no postback;
// once a postback is perfoemd this is not hit, modal not populated
$('#editModal').modal({
keyboard: true,
backdrop: "static",
show: false
}).on('show.bs.modal', function (e) {debugger
var var1= $('#hfVar1').val();
var var2= $('#hfVar2').val();
//make ajax call to populate items
populateMPOOEdit(var1, var2);
});
....
});
//This is the button in modal that causes postback
<div class="modal-footer">
<div id="divEditButtons" style="text-align: center;">
<button id="btnCancel" class="btn btn-info2" data-dismiss="modal" aria-hidden="true" aria-label="Cancel">Cancel</button>
<button id="btnSubmit" class="btn btn-primary" aria-hidden="true" aria-label="Update">Update</button>
</div>
</div>
// "Submit" button's click handler
$(document).on("click", "#btnSubmit", function (event) {
// Validate data (client side validation)
var isValid = validateUpdate();
// Also need a server side validation checking for duplicate name, using ajax to do this
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: '<%= ResolveUrl("services/mpoo.asmx/NameExists") %>',
cache: false,
data: JSON.stringify({ "Name": name }),
}).done(function (data) {
var result = data.d;
if (result != '') {
nameExists = JSON.parse(data.d);
if (nameExists == "true") {
$("#lblErrName").text("Duplicate Name");
$("#lblEditErrName").show();
isValid = false;
}
if (isValid) {
__doPostBack('btnSubmit', JSON.stringify({
action: "SaveUpdate", Var1: var1, ..., Varn: varn
}));
$('#editModal').modal('hide');
}
}
});
return false; // to prevent modal from closing if there are errors on page
});
Create a function like this:
//basically everything you had in your document.ready function
function myJsFunc() {
// This populates the jQuery data table
showTable(somthing, anotherThing);
// This is executed as long there is no postback;
// once a postback is perfoemd this is not hit, modal not populated
$('#editModal').modal({
keyboard: true,
backdrop: "static",
show: false
}).on('show.bs.modal', function (e) {debugger
var var1= $('#hfVar1').val();
var var2= $('#hfVar2').val();
//make ajax call to populate items
populateMPOOEdit(var1, var2);
});
....
}
Then in your Page_Load event handler in your codebehind, try putting this:
Page.ClientScript.RegisterStartupScript(this.GetType(), "some random name for your script", "myJsFunc();", true);
I have a link on clicking it is sending ajax request and getting response successfully which is html file and I am appending to a div, but I need to show that div as modal popup and I tried something below.
in html file
<a th:if="${ratingSummary}" href="#" class="small dark account review_ratings_login">Login to write a review</a>
<div id="login_for_review" data-toggle="modal" data-target="#reviewLoginModal"></div>
in js file
$(document).on('click', '.review_ratings_login', function () {
var $data = $('#review_product_id span').text();
var url = '/mycompany/login/'+$data;
$.ajax({
type: 'GET',
url: url,
success: function (output) {
$('#login_for_review').html(output).modal('show');// I tried to show this response as modal popup
},
error: function(output){
alert("fail");
}
});
});
output file
<div class="centerForm modal fade" role="dialog" style="margin-left: 35%;" id="reviewLoginModal">
<div class="modal-dialog modal-sm" >
<div class="modal-content">
// here I have login form
</div>
</div>
but I am not getting this html output as modal pup instead I am getting black screen can anyone help me how to do this?
In Bootsrap modal popup, You can use plain way to show modal which don't need pre-defined modal div container . see at modal
For E.g
$.ajax({
url: "url",
type: 'POST',
dataType: "html",
data:{id:params},
success: function(data, status, xhr) {
if(data==""){
window.location.href="/";
}
else{
BootstrapDialog.show({
title: "Modal Tital",
message: function(dialogRef){
$mydata = $($.parseHTML(data));
return $mydata;
},
onshow: function(dialog){
// and css change if need, eg.
dialog.$modalHeader.css("float","none");
},
onshown:function(dialog)
{
// event after shown
},
onhide:function(dailog)
{
// event on hide
}
});
}
},
statusCode: {
401: function () {
alert("Your session has been expired");
}
}
});
I solved this problem by creating modal and by removing data-toggle and data-target and just appending response to that modal div
Code For modal div
<div id="login_for_review" class="modal hide" role="dialog">
</div>
Code For hyperlink
<a th:if="${ratingSummary}" href="#" class="small dark account review_ratings_login">Login to write a review</a>
Code For ajax call
$(document).on('click', '.review_ratings_login', function () {
var $data = $('#review_product_id span').text();
var url = '/mycompany/login/'+$data;
$.ajax({
type: 'GET',
url: url,
success: function (output) {
$('#login_for_review').html(output).modal('show');//now its working
},
error: function(output){
alert("fail");
}
});
});
On my page I have a section like this:
using (Html.BeginForm("AddSubTor", "Maintor", FormMethod.Post, htmlAttributes: new { ID = "frmSubTors" }))
{
#Html.AntiForgeryToken()
#Html.Partial("_SublistPartial")
<div class="row" style="margin-top: 15px;">
<div class="col-sm-12 col-md-12 col-lg-12 text-center ">
#* submit button here *#
<input type="submit" class="btn btn-default" value="Add" />
</div>
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
}
Instead of using the submit button, I would replace it then with an image that looks like a button, could I also do the same submit in a jquery function. Like in the click event of that button-like image? Would the data I'm submitting still be submitted?
The reason I want to do this is that in the partial I have two radio buttons. On both I have some Jquery code for retrieving data and other stuff.
If I use a simple submit button I can set the radiobuttons but there is no click event thus the data is not retrieved and other stuff is not done.
So if I can use Jquery, then I can simple call the functions that the radiobutton-click events call and so get my data.
[edit]
I'm kind of looking for something like this:
$.Ajax({
url: 'controller/action',
type: 'POST',
success: function(data) {
$('#frmSubTors').html(data);
}
}).done(function() {
// do my other stuff here
});
Would this work too?
Yes, you can use jQuery to submit the form when the image is clicked.
Replace the submit button with the image and give it an id.
<div class="col-sm-12 col-md-12 col-lg-12 text-center ">
#* submit button here *#
<img id="myImage" src="blah.jpg" />
</div>
Then have jQuery respond to a click event:
$(document).ready(function() {
$("#myImage").click(function() {
$("#frmSubTors").submit();
}
}
More click event info for jQuery: http://www.w3schools.com/jquery/event_click.asp
Yes, If you use $('#frmSubTors').submit(), The form will be submitted wit all the fields.
You could submit the form using your image event.
$('img').on("click", function () {
$('#frmSubTors').submit();
});
You can submit form with ajax like following.
$("#your_img_id").click(function () {
$.ajax({
type: 'POST',
url: '/Maintor/AddSubTor',
data: $(this).serialize(), //serializes the form's elements.
success: function (data) {
// do your other stuff here after succesful form submit
}
});
});
If your form has <input type="file"> then do like following.
$("#your_img_id").click(function () {
var formData = new FormData($('#frmSubTors')[0]);
$.ajax({
type: 'POST',
url: '/Maintor/AddSubTor',
data: formData,
cache: false,
contentType: false,
processType: false,
success: function(data) {
// do your other stuff here after succesful form submit
}
});
});
Hope this will help you.
i have a several html buttons (not within a form).
When clicked they call a JavaScript function that after conformation, runs an ajax call.
This part all works OK, but i would then like to change the class of whichever button was clicked on success of the ajax call.
i have tried various methods seen on stackOverflow, but none of them seem to work...
can i please ask what am i doing wrong?
here is the simplified HTML (buttons)
<button class="btn btn-primary" onclick="primaryImage(4107,19372,'/abbie1.jpg'); return false;">
set as profile image
</button>
<button class="btn btn-primary" onclick="primaryImage(4107,19373,'/abbie2.jpg'); return false;">
set as profile image
</button>
<button class="btn btn-success" onclick="primaryImage(4107,19374,'/abbie3.jpg'); return false;" disabled="disabled">
profile image
</button>
Please note: the last button is already the active/success button, and i would also like to remove the class on success too (as only one should be active), but that is maybe my next stage....
here is the javaScript, (i have left in some of the methods i have tried, but commented them out)
function primaryImage(eid,pid)
{
if (confirm("Are you sure you wish to use this as your profile image?"))
{
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "ajax_photo.php",
data: "action=primary&eid="+eid+"&pid="+pid,
//context: this,
success: function(data){
if(data.result=='success')
{
alert('The image is now set as the profile image');
//$('button').click(function(){
// $(this).addClass('btn-success');
//});
//$('button').on(data.result=='success', function(e) {
// $(this).toggleClass("btn btn-success"); //you can list several class names
// e.preventDefault();
//});
//$(this).removeClass('btn-primary').addClass('btn-success');
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
}
I would be very grateful for any advice of what i am doing wrong
(as you can see, i am not too good with JS (yet))
Thanks!
Ford
As noted in your commented out code, you are binding the click event after click event has already been fired.
I would suggest you to pass a reference of the button that was clicked in the primaryImage() function itself as such:
<!-- In your HTML -->
<button class="btn btn-success" onclick="primaryImage(this, 4107,19374,'/abbie3.jpg'); return false;" disabled="disabled">
profile image
</button>
function primaryImage(button, eid,pid){
/** ... */
Then using that referenced button, you can add or remove CSS classes to the element, as well as the siblings of the element (using jQuery's siblings() method).
//your ajax call
success: function(data){
if(data.result=='success') //make sure this really is success
{
alert('The image is now set as the profile image');
$(button).removeClass('btn-primary').addClass('btn-success');
$(button).siblings('button').removeClass('btn-success').addClass('btn-primary');
}
}
As you don't use the jQuery .click() event, I think you need to pass the button in your function args.
So your button will look like
<button class="btn btn-primary" onclick="primaryImage(this, 4107,19373,'/abbie2.jpg'); return false;">
set as profile image
</button>
Then your function will be like
function primaryImage(el, eid,pid)
{
if (confirm("Are you sure you wish to use this as your profile image?"))
{
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "http://anzvirtuel.org",
data: "action=primary&eid="+eid+"&pid="+pid,
//context: this,
success: function(data){
if(data.result=='success')
{
$(el).addClass('btn-success');
alert('The image is now set as the profile image');
// keep doing whatever you want...
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
}
As I have not fully understood your commented JS I'll let you put the code you want, just remember that your button will be accessible in jQuery with $(el).
Hope it may helps you
You should pass the clicked element to the primaryImage() function, and use it on success to do whatever you like.
<button class="btn btn-primary" onclick="primaryImage(this, 4107,19372,'/abbie1.jpg'); return false;">set as profile image</button>
And in your JS
function primaryImage(element, eid,pid)
{
[...]
success: function(data){
if(data.result=='success')
{
$(element).addClass('btn-success');
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
[...]
}
You could use data-* attributes instead of onclick (MDN Documentation) and then access those throught jQuery, so your code is more clean and HTML / JS are separated.
Try this code, I've created three data attributes (data-eid, data-pid and data-image) for your params and also replaced your JS to make the whole stuff work with those data attributes. Those attributes can be accessed with following jQuery code - var eid = $(this).attr('data-eid'); as an example
This line of code removes the btn-primary class from the clicked button, adds a btn-success class to it and disables it, so it can't be toggled again.
pushedBtn.removeClass("btn-primary").addClass("btn-success").prop("disabled", true);
HTML
<button class="btn btn-primary" data-eid="4107" data-pid="19372" data-image="/abbie1.jpg">
profile image
</button>
<button class="btn btn-primary" data-eid="4107" data-pid="19373" data-image="/abbie2.jpg">
profile image
</button>
<button class="btn btn-primary" data-eid="4107" data-pid="19374" data-image="/abbie3.jpg">
profile image
</button>
JS
$(".btn").click(function (e) {
if (confirm("Are you sure you wish to use this as your profile image?")) {
var eid = $(this).attr('data-eid'); //like 4107
var pid = $(this).attr('data-pid'); //like 19372
var image = $(this).attr('data-image'); //like /abbie1.jpg
var pushedBtn = $(this);
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "ajax_photo.php",
data: "action=primary&eid=" + eid + "&pid=" + pid,
//context: this,
success: function (data) {
if (data.result == 'success') {
alert('The image is now set as the profile image');
pushedBtn.removeClass("btn-primary").addClass("btn-success").prop("disabled", true);
} else {
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
});
I'm having an issue with the code below where if I put an invalid email address in it will properly show the signUpWarning alert the first time but if I close that box and try the same invalid email it won't pop back up. Any ideas?
$(document).ready(function() {
//if submit button is clicked
$('#submit_btn').click(function(e) {
e.preventDefault();
var email = $('#email').val();
if (!is_valid_email(email)){
$("#signUpWarning").show();
}else{
$.ajax({
url: "process.php",
type: "post",
data: "email=" + email,
success: function() {
$("#signUpWarning").hide();
$("#signUpAlert").show();
}
});
}
});
});
function is_valid_email (email)
{
return /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email);
}
The code for the alert box is:
<div class="alert alert-block alert-error hide" id="signUpWarning"><!--Use: $("#signUpWarning").show(); to show this alert-->
<a class="close" data-dismiss="alert">×</a>
<h5 class="alert-heading">Sorry!</h5> Your e-mail address was not valid, please try again.
</div>
Check that you're not removing the element from the DOM when closing the alert.
console.log($("#signUpWarning")); before the $("#signUpWarning").show(); should help determine if that's what's happening.