get a problem with after success ajax and load the div.
Here's the code:
<script>
$('.delete').click(function(e){
e.preventDefault();
var id = $(this).attr('id');
if (confirm('Delete this user?') == true) {
$.ajax({
type: "POST",
data: {_method: "DELETE"},
url: 'manage-staff-roles/' + id, //resource
beforeSend: function(){
$('.loader-wrap').removeClass('hiding hide');
},
success: function() {
$('.loader-wrap').addClass('hiding hide');
$('#table').load(location.href + " #table");
Messenger().post({
message: 'Success.',
type: 'success',
showCloseButton: true
});
}
});
}
else
{
return;
}
});
</script>
Here is my html:
<div id="table">
#foreach($staffroles as $staffrole)
{{ $staffrole->id }}
{{ $staffrole->name }}
<a class="edit" id="staffroles/{{ $staffrole->id }}/edit" href="manage-staff-roles/{{ $staffrole->id }}/edit">
Edit </a>
|
<a class="delete btn" id="{{ $staffrole->id }}" >
Delete </a>
#endforeach
</div>
after the ajax success and do all the function perfectly (including reload the specific div). But the problem is my div that contain a delete button is become unusable but the edit button is working).
You need to add click handler using .on() for dynamically created buttons. Modify your delete button click handler as shown below
$(document).on('click','.delete',function(e){
e.preventDefault();
var id = $(this).attr('id');
if (confirm('Delete this user?') == true) {
$.ajax({
type: "POST",
data: {_method: "DELETE"},
url: 'manage-staff-roles/' + id, //resource
beforeSend: function(){
$('.loader-wrap').removeClass('hiding hide');
},
success: function() {
$('.loader-wrap').addClass('hiding hide');
$('#table').load(location.href + " #table");
Messenger().post({
message: 'Success.',
type: 'success',
showCloseButton: true
});
}
});
}
else
{
return;
}
});
The problem is that the .load method of jQuery, will add new html and this will override any event handlers that were added previously, you will need to re-add the event handlers for button (in case it is overriden by .load) so as to continue being re-usable.
Another alternative is to add the event handlers (for button) on parent element and delegate (via jQuery.on method with selector)
Hope this helps, comment for further info if needed
Related
HTML:
<a class="mr-2 mb-2 btn btn-outline-primary btn-sm" onclick="edit_init(this)" href="#4CE10703YB"><i class="ti-info"></i></a>
jQuery:
function edit_init(anchor){
$("#edModal").html("");
ref = anchor.href.substr(anchor.href.lastIndexOf('/') + 1);
ref = ref.replace(/^#/, "");
$.post("modal.php",{ajax_get_edModal:1,ajax_modal_for:ref},function(data){
$("#edModal").html(data);
});
}
So everything is working fine, but now I want to change the html() inside that anchor tag to something like "loading.." and disable it during the duration of the ajax request.
You can apply below changes to your function, in order to achieve your task.
function edit_init(anchor){
$prevHtml = $(anchor).html();
$href = $(anchor).attr('href');
$(anchor).removeAttr('href');
$(anchor).html('Loading....');
$(anchor).attr('disabled',true);
$("#edModal").html("");
ref = anchor.href.substr(anchor.href.lastIndexOf('/') + 1);
ref = ref.replace(/^#/, "");
$.post("modal.php",{ajax_get_edModal:1,ajax_modal_for:ref},function(data){
$("#edModal").html(data);
$(anchor).html($prevHtml);
$(anchor).removeAttr('disabled');
$(anchor).attr('href',$href);
});
}
Use beforeSend to do something while ajax request, for example:
$.ajax({
type: 'post',
url: 'example.php',
data: form.serialize(),
beforeSend: function() {
$('.yourTag').html('loading...');
},
success: function(data) {
$('.yourTag').html(data);
},
error: function() {
$('.yourTag').html('error');
}
});
I am working on opencart. I dont want my users to buy multiple products they can buy only 1 product with 1 customer id, so for this i want my add to cart button to help me. I want this button to be disabled (read only) if add to cart process is performed successfully.
HTML:
<button type="button" id="button-cart" data-loading-text="<?php echo $text_loading; ?>" class="btn btn-primary btn-lg btn-block"><?php echo $button_cart; ?></button>
Jquery:
<script type="text/javascript"><!--
$('#button-cart').on('click', function() {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('#product input[type=\'text\'], #product input[type=\'hidden\'], #product input[type=\'radio\']:checked, #product input[type=\'checkbox\']:checked, #product select, #product textarea'),
dataType: 'json',
beforeSend: function() {
$('#button-cart').button('loading');
},
complete: function() {
$('#button-cart').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
if (json['error']['option']) {
for (i in json['error']['option']) {
var element = $('#input-option' + i.replace('_', '-'));
if (element.parent().hasClass('input-group')) {
element.parent().after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
} else {
element.after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
}
}
}
if (json['error']['recurring']) {
$('select[name=\'recurring_id\']').after('<div class="text-danger">' + json['error']['recurring'] + '</div>');
}
// Highlight any found errors
$('.text-danger').parent().addClass('has-error');
}
if (json['success']) {
$('.breadcrumb').after('<div class="alert alert-success">' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
$('#cart > button').html('<i class="fa fa-shopping-cart"></i> ' + json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
}
});
});//--></script>
I know this will do the trick
$(this).attr('disabled', true);
But iam not finding the best position for it. I want the button to be disabled if the validation is all done and product is entered in cart area
jQuery.attr()
Get the value of an attribute for the first element in the set of matched elements.
whereas,
jQuery.prop()
Get the value of a property for the first element in the set of matched elements.
Before jQuery 1.6 , the attr() method sometimes took property values into account when retrieving some attributes, which caused in inconsistent behavior. And thus, the prop() method was introduced. As of jQuery 1.6. , the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
According to your code you are highlighting error by $('.text-danger').parent().addClass('has-error');. So
you can use prop('disabled', true) instead of $(this).attr('disabled', true); and add it to just after $('.text-danger').parent().addClass('has-error');
$('.text-danger').parent().addClass('has-error');
$(this).prop('disabled', true)
I see that you are relying on the response from your service call to validate success or error.
In that case it will be better to disable the button as soon as your service is called, and wait for response.
After response if your validation is successful, then no worries, else re-enable button and notify user the error and ask to make changes if required.
So the code could be like this,
$('#button-cart').on('click', function() {
var _button_ref = this;
$(_button_ref).attr('disabled', true);
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('#product input[type=\'text\'], #product input[type=\'hidden\'], #product input[type=\'radio\']:checked, #product input[type=\'checkbox\']:checked, #product select, #product textarea'),
dataType: 'json',
beforeSend: function() {
$('#button-cart').button('loading');
},
complete: function() {
$('#button-cart').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
// your logic
$(_button_ref).attr('disabled', 'false');
}
if (json['success']) {
// your logic
}
}
});
Also, it will be better if you have error call back function, to handle if service fails.
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
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?
If i have something like:
<form method="post" id="customForm" action="">
//stuff
<div id="copiar">
<button class="button" href="#" id="btnAdd0">
<span class="icon icon3"> </span>
</button>
<button class="button" href="#" id="btnDel0">
<span class="icon icon58"> </span>
</button>
<button class="submeter">
<span class="label">Send</span>
</button>
</div>
</form>
and:
<script type="text/javascript">
$(document).ready(function() {
$("#customForm").submit(function() {
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "validation.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data, data1) {
//stuff
});
return false;
});
});
</script>
At the moment, the three buttons send the form. My idea is only permit the submit action in this button:
<button class="submeter">
<span class="label">Send</span>
</button>
I already tried $("#customForm > #copiar > button.submeter").submit(function() {
but the page is reloaded. So isn't working.
Any idea ?
You have to stop the other buttons from submitting first and then do your submit. Also when using an ID for your selector there really isn't any need to combine it with another ID like #customForm > #copiar "
Try this:
$(document).ready(function() {
$("#customForm").submit(function(e) {
e.preventDefault();
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "validation.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data, data1) {
//stuff
}
});
});
$("#customForm button").click(function(e) {
var me = $(this);
e.preventDefault();
if(me.hasClass("submeter")) $("#customForm").submit();
});
});
And as has already been pointed out, you don't need/want the href="#"
In order to prevent the default behavior of the form, you must use preventDefault() as follows:
$(document).ready(function() {
$("#customForm").submit(function(e) {
e.preventDefault();
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "validation.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data, data1) {
//stuff
});
});
$("#customForm button.submeter").click(function() {
$("#customForm").submit();
});
});
What is exactly the purpose of first two button element with the href attribute? I suspect you're using a button instead of a regular link only for a formatting/visual reason.
Anyway for your purpose, just add the attribute type="submit" to the last button and remove the submit handler you've defined for this button, it should work fine.
edit. you also need to call the preventDefault() method to stop page reload, as pointed out by phil klein