Change ajax default alert box style - javascript

Is there a way I could change the default ajax alert box? I currently have the code below, that deletes a user and reloads the current page. It works, but I would like to add some styling to the alert box that it triggers before the user is actually deleted.
function deleteUser(id) {
var action = confirm("Are you sure you want to delete this student?");
if (action != false) {
$.ajax({
url: '{% url "student-delete" %}',
data: {
'id': id,
},
dataType: 'json',
success: function (data) {
if (data.deleted) {
$("#userTable #user-" + id).remove();
window.location.reload()
}
}
});
}
}
I tried changing the confirm to
function deleteUser(id) {
var action = bootstrap.confirm("Are you sure you want to delete this student?");
if (action != false) {
$.ajax({
url: '{% url "student-delete" %}',
data: {
'id': id,
},
dataType: 'json',
success: function (data) {
if (data.deleted) {
$("#userTable #user-" + id).remove();
window.location.reload()
}
}
});
}
}
This displayed nothing.

You cannot style the custom confirmation box. It varies from browser to browser. If you want something custom you can build out one yourself using HTML and CSS. For example attach click events for yes button and for a no button and based on that you can make the delete

Related

Refreshing Data Div inside Ajax request

I am trying to create a profile picture editor with a dropdown having two options:
Update your Profile Picture
If there is any profile picture it will show Delete options otherwise it will hide this options
template code:
<div class="dropdown-menu">
<a class="dropdown-item"><input name="input_file" type="file" id="profile-pic-upload" style="display: none;" />
<label for="profile-pic-upload">Upload Profile Picture</label>
</a>
{% if user_profile.profile_pic %}
<a class="dropdown-item delete" href="javascript:" style="font-size : 14px;">Delete</a>
{% endif %}
</div>
JS code:
$(".delete").click(function () {
$('.loading').show();
var url = "{% url 'user-profile-image-delete' %}";
$.ajax({
type: 'POST',
url: url,
data: $("#new_form").serialize(),
cache: false,
success: function (data, status) {
$('#imagePreview').css('background-image', 'url('+'{% static 'assets/img/user-64x.png' %}'+')');
if (data['status'] == "success") {
}
else {
toastr.error(data.msg);
}
}
});
});
$("#profile-pic-upload").change(function () {
var input_detail = this;
var data = new FormData();
var file = this.files[0];
data.append("file", file);
$.ajax({
type: 'POST',
data: data,
contentType: false,
processData: false,
url: $("#profile-file-upload").data('action'),
cache: false,
success: function (data, status) {
if (data['status'] == true) {
toastr.success(data.msg);
var randomId = new Date().getTime();
$('#imagePreview').css('background-image', 'url(' + data.profile_pic + '?random=' + randomId + ')');
}
else {
toastr.error(data.msg);
}
}
});
});
But I am facing one issue: even if I click the delete option the dropdown is not refreshing and it still shows an option for deleting it. It only goes once I refresh the page.
Same way if there is no profile picture it only shows Upload Profile pic. If I update an image the dropdown will not shows the delete option. To see this I need to refresh the page.
How to avoid page reload to refresh dropdown contents?
I understand your problem. You can easily solve this issue in your ajax call success.
What you need to do is just simple hide and show using jquery or javascript.
Lets say user already has a profile pic and the person clicks on delete option and ajax call is success then you should hide the delete option. (you can also remove it but later you will have to create it via javascript)
$(".delete").click(function () {
$('.loading').show();
var url = "{% url 'user-profile-image-delete' %}";
$.ajax({
type: 'POST',
url: url,
data: $("#new_form").serialize(),
cache: false,
success: function (data, status) {
$('#imagePreview').css('background-image', 'url('+'{% static 'assets/img/user-64x.png' %}'+')');
if (data['status'] == "success") {
//$(".delete").hide(); // this will hide your delete option
//Instead of hiding we are now removing the button then generating the button dynamically via javascript.
$(".delete").remove();
// But note one thing if we use class then it will hide/delete all elements with class of delete. so it's better to use id for unique elements.
}
else {
toastr.error(data.msg);
}
}
});
});
For the other case where there is no profile pic and the user updates profile pic then you should create a dropdown menu and append it to the dropdown.
$("#profile-pic-upload").change(function () {
var input_detail = this;
var data = new FormData();
var file = this.files[0];
data.append("file", file);
$.ajax({
type: 'POST',
data: data,
contentType: false,
processData: false,
url: $("#profile-file-upload").data('action'),
cache: false,
success: function (data, status) {
if (data['status'] == true) {
toastr.success(data.msg);
$(".delete").remove();
let dropdown_menu_item = '<a class="dropdown-item delete" href="javascript:" style="font-size : 14px;">Delete</a>'
$('.dropdown-menu').append(dropdown_menu_item);
var randomId = new Date().getTime();
$('#imagePreview').css('background-image', 'url(' + data.profile_pic + '?random=' + randomId + ')');
}
else {
toastr.error(data.msg);
}
}
});
});
this should work but i think you should handle that show or hide dropdown using javascript by checking first if the profile pic is updated if there then show delete button else hide the delete button and when user updates profile pic then show delete button.

How to delay ajax call on keypress?

I have an input box where I'm doing an AJAX GET to check if the email is within my database. I'm simply checking for an email address and if it's within the database, we retrieve true/else false. So depending on the return I display either a tick or cross image.
$.ajax({
url: '/api/user/emailaddress/' + emailAddress,
type: 'GET',
dataType: 'json',
success: function(data) {
if (data===true) {
$(".email-address-validator").removeClass("success");
$(".email-address-validator").addClass("error");
}
}
});
Each time a key is pressed within the input box field, this gets called. The problem that I thought might prop up is if someone looks at this file and see's that I'm doing an AJAX GET request on the field that they might just keep pressing keys on that particular input box.
Q: How can I set a timeout on this, for around 5 seconds so a user doesn't just keep spamming the box?
You could set a flag to handle this scenario. Something like this is much better than a timer.
var waitingForResponse= false;
function isValidEmail () {
if (!waitingForResponse) {
waitingForResponse = true;
$.ajax({
url: '/api/user/emailaddress/' + emailAddress,
type: 'GET',
dataType: 'json',
success: function(data) {
waitingForResponse= false;
if (data===true) {
$(".email-address-validator").removeClass("success");
$(".email-address-validator").addClass("error");
}
}
});
}
}
This design pattern will prevent subsequent requests until the first response is received. If you need a further interval between requests than this suggestion, then you can wrap the waitingForResponse flag in a setTimeout function inside the success callback. Like so:
var waitingForResponse= false;
function isValidEmail () {
if (!waitingForResponse) {
waitingForResponse = true;
$.ajax({
url: '/api/user/emailaddress/' + emailAddress,
type: 'GET',
dataType: 'json',
success: function(data) {
setTimeout(function () {
waitingForResponse= false;
}, 5000);
if (data===true) {
$(".email-address-validator").removeClass("success");
$(".email-address-validator").addClass("error");
}
}
});
}
}

Form submitting to wrong function when changing class dynamically

I'm sure there's a simple explanation for this but I haven't been able to find the right words to use when searching for answers.
When users fill out the form .InvoiceForm it submits via Ajax. After it's submitted remove the .InvoiceForm class and add .UpdateInvoice. When a user submits a .UpdateInvoice form it explains that they are about to make a change and they have to click to say "Yes I want this to be updated".
The issue is that unless I refresh the page so that the form is loaded with the .UpdateInvoice form, I don't get the confirmation which means it's still submitting as a .InvoiceForm form. Is there anything I can do to fix this?
Edit to show code:
Code that runs if there's no record
$('.InvoiceForm').submit(function(e) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
$(this).removeClass('InvoiceForm');
$(this).addClass('UpdateInvoice');
$(this).find('.btn').val('Update');
$(this).find('.id').val(data.invoice_id);
$(this).find('.btn').removeClass('btn-default');
$(this).find('.btn').addClass('btn-danger');
$(this).find('.AddRow').removeClass('hide');
$(this).find('.invoiceDetails').html(data.returnedData);
$(this).parent().next().find('.grade').focus();
}
});
return false;
};
Code that runs if there is a record being updated
$('.UpdateInvoice').submit(function(){
var r = confirm("Are you sure you want to make this update?");
if (r == true) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
alert('This row has been updated');
$(this).find('.total').html(data);
}
});
} else {
}
return false;
});
The function for .UpdateInvoice doesn't run unless I refresh the page.
Thanks for your help.
You bind a click event on '.UpdateInvoce' before it even being created, hence it'll not work. I think you need to use .live() in order to make it works. See document here: jQuery's live()
HTML:
<button id="click_me" class="new">Click Me</button>
<div class="result" />
Script:
$(function () {
$('.new').click(function (e) {
$('.result').text("Im new !");
$(this).removeClass("new");
$(this).addClass("update");
// Bind UpdateInvoice's click event on the fly
$('.update').live(bindUpdate());
});
function bindUpdate() {
$('.update').click(function (e) {
$('.result').text("Update me !");
});
}
});
jsfiddle's demo

model validation summary errors alert box is disabled on .hide()

I have a postcode finder on my mvc web application form which is optional. If I dont get a post code match I appened the .validation-summary-errors with my own custom error message. Once the error has been corrected I remove all instances of class postcode in .validation-summary-errors and apply the hide method. The problem is when hiding the validation-summary-errors div disables the validation popup to show other form errors when submitting the form.
my javascript code
$("#AddressFinder").click(function () {
var postcode = $("#Address_Postcode").val();
$(".postcode-error").remove();
$(".validation-summary-errors").hide();
if (!postcode) {
$(".validation-summary-errors ul").append("<li class='postcode-error'>Please include a postcode to search.</li>");
$(".validation-summary-errors").show();
}
else {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/Postcode/GetAddress",
data: "{ 'postcode':'" + postcode + "' }",
success: function (data) {
if ($.isEmptyObject(data)) {
$(".validation-summary-errors").append("<li class='postcode-error'>There are no addresses matching your postcode</li>");
$(".validation-summary-errors").show();
}
else {
vm.addresses(data);
addressList.show();
}
}
});
}
});
how can i hide the valiidation-summary-errors div without it disabling when submitting the form to the controller?
Managed to fix my issue. Your not suppose to use hide() or show(). Just add or remove the validation-summary-validation.
$("#AddressFinder").click(function () {
var postcode = $("#Address_Postcode").val();
if (!postcode) {
$(".validation-summary-errors ul").append("<li class='postcode-error'>Please include a postcode to search.</li>");
$(".validation-summary-errors").removeClass("validation-summary-valid");
}
else {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/Postcode/GetAddress",
data: "{ 'postcode':'" + postcode + "' }",
success: function (data) {
if ($.isEmptyObject(data)) {
$(".validation-summary-errors").append("<li class='postcode-error'>There are no addresses matching your postcode</li>");
$(".validation-summary-errors").removeClass("validation-summary-valid");
}
else {
vm.addresses(data);
addressList.show();
$(".postcode-error").remove();
$(".validation-summary-errors").addClass("validation-summary-valid");
}
}
});
}
});
This way you still get the model validation messeges working when the form is submitted.

How to manage an event unload

I want to insert in my page an event that trigger when the window close or change except that in the case that has been triggered by a submit button of a particular submit which bring in an analogus page. I tried the follow but it doesn't work. (prova is the name of submit).
$(window).bind("unload", function (event) {
alert('1');
if (event.target.tagName != "prova") {
alert('2');
var postData = {
'chat_message': "I left"
};
$.ajax({
type: "POST",
dataType: "json",
url: base_url + "chat/ajax_add_message/" + chat_id + "/" + user_id,
data: postData,
success: function (data) {
get_messages();
}
});
}
});
Do you really have HTML element with tag "prova" ?
event.target.tagName != "prova"
Maybe you need to check className or id?

Categories