unbind and off doesn't work before call ajax-Jquery - javascript

I have an element with class.btn-confirm and handel click event like this in MasterLayout (ASP.NET MVC)
$(document).on('click', '.btn-confirm', function () {
$.ajax({
url: $('#url').data('deleteurl'),
type: "POST",
data: { code: $('.btn-confirm').data('code') },
success: function (data) {
ShowMessage(data.message, 'success');
},
error: function (responce) {
ShowMessage('error', 'error');
}
});
});
and I want override this event in Other Page like this :
$('.btn-confirm').unbind('click');
$('.btn-confirm').off('click');
$(document).on('click', '.btn-confirm', function ()
{
...}
but when I clicked on button , run two functions , I want disable first event handle.
I used unbind and off but it does not work.

If you bind the event on document you must then also unbind it on document
$(document).off('click', '.btn-confirm');
$(document).on ('click', '.btn-confirm', ...new function...

Related

Can't delete data after 10 entries in AJAX, JQuery and javascript/php

I have 10 rows with data inserted and I'm able to delete any of those, but after I insert from 11th row onwards I can't delete any of the rows after the 10th.
EDIT (I CAN'T DELETE ANYTHING WHEN THE RESPONSIVE FORM IS SHOWING)
$(document).ready(function(){
$('#list').dataTable({
responsive: true
});
$('.delete_piece').click(function(){
_conf("Are you sure to delete this piece?","delete_piece",[$(this).attr('data-id')])
})
})
function delete_piece($id){
start_load()
$.ajax({
url:'ajax.php?action=delete_piece',
method:'POST',
data:{id:$id},
success:function(resp){
if(resp==1){
alert_toast("Data successfully deleted",'success')
setTimeout(function(){
location.reload()
},1500)
}
}
})
}
DELETE FUNCTION AJAX
if($action == "delete_piece"){
$delsete = $crud->delete_piece();
if($delsete)
echo $delsete;
}
DELETE FUNCTION FOR THE ADMIN (ME)
function delete_piece(){
extract($_POST);
$delete = $this->db->query("DELETE FROM mro_inventory where id = ".$id);
if($delete){
return 1;
}
}
Consider the following.
$(function() {
function delete_piece($id) {
start_load()
$.ajax({
url: 'ajax.php?action=delete_piece',
method: 'POST',
data: {
id: $id
},
success: function(resp) {
if (resp == 1) {
alert_toast("Data successfully deleted", 'success')
setTimeout(function() {
location.reload()
}, 1500);
}
}
});
}
$('#list').dataTable({
responsive: true
});
$('tbody').on("click", ".delete_piece", function(e) {
_conf("Are you sure to delete this piece?", "delete_piece", [$(this).attr('data-id')])
});
});
This uses the .on() method to delegate the click event to a class.
Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated event handlers to avoid the need to frequently attach and remove event handlers.
See more: https://api.jquery.com/on/
It was not clear from your post what the HTML structure looks like; yet, you are using DataTables, so I know there should be a Table Body element that should be present.
this is how I solved the problem!!
$(document).ready(function() {
$('#list').dataTable({
responsive: true
});
$('tbody').on("click", ".delete_piece", function() {
_conf("Are you sure to delete this piece?","delete_piece",[$(this).attr('data-id')])
})
})
function delete_piece($id){
start_load()
$.ajax({
url: 'ajax.php?action=delete_piece',
method: 'POST',
data: {
id:$id
},
success: function(resp) {
if (resp == 1) {
alert_toast("Data successfully deleted",'success')
setTimeout(function() {
location.reload()
}, 1500)
}
}
})
}

create onclick event for multiple ids

I have written a js function:
$(document).on('click', '#id1', function () {
$.ajax({
type: "POST",
url: "/url",
data: { uInput: 'id1' },
success: function (response) {
some code....
},
error: function (error) {
console.log(error);
}
});
});
Problem is, since I have more clickable objects with various IDs, i wanted to create a single script/function that would accept onclick event from not only #id1, but also #id2, #id3 etc...
I tried following advice found here: https://stackoverflow.com/a/18508894/11271927
and here https://stackoverflow.com/a/18508907/11271927
but whenever I would edit the code to acomodate my code structure, it wouldnt work.
var options = {
id1: 'id1',
id2: 'id2',
id3: 'id3',
id4: 'id4'
};
$('.options').click(function () {
$.ajax({
type: "POST",
url: "/url",
data: options[this.id],
success: function (response) {
some code....
},
error: function (error) {
console.log(error);
}
});
});
Essentially, this code doesnt do anythign on click.
If you know what I have missed or done wrong, please help.
If you want to have one function that will have a click listener on several elements (for example by class) you can try it like this:
<button class="button" id="id1">A</button>
<button class="button" id="id2">B</button>
<button class="button" id="id3">C</button>
<script>
$(document).on('click', '.button', function () {
$.ajax({
type: "POST",
url: "/url",
data: {
uInput: this.getAttribute('id'),
},
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
});
</script>
You can set a single click event listener on the document and use a conditional inside its function to apply the same statement block to any groups of elements.
For example, you could filter for targets that have id begining with the string "id" like this (core js):
document.addEventListener('click', event => {
if (event.target.id.indexOf('id') == 0) {
// commands to apply to those elements;
} // end if #id* click;
// any number of other groups or individual elements can be added, each with a conditional to filter the required ones.
}); // end event listener
If you require more specificity, refine the conditional, for example (inside the document event listener function):
const id=event.target.id;
if (id == "id1" || id == "id3" || id == "somethingElse") {
// relevant statements;
};
I generally use document event listeners by default, there is no extra computational cost and I find the single event listener easier to maintain.

.focusout() fires twice on second event jQuery

When I am using the .focusout() function in jQuery it seems to fire twice when I trigger the event for the second time, here is an example of my code:
$(document).ready(function() {
var baseUrl = "http://annuityadvicecentre.dev/";
if($('html').hasClass('ver--prize-soft')) {
$('#home_telephone').focusout(function () {
var softResponse = {};
var inputVal = $(this).val();
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type: 'POST',
url: baseUrl + "lookup",
data: {
number: inputVal,
phone_type: "mobile",
},
error: function() {
console.log('POST Error: Mobile');
},
}).done(function(data) {
// you may safely use results here
softResponse.isMobile = data;
});
$.ajax({
type: 'POST',
url: baseUrl + "lookup",
data: {
number: inputVal,
phone_type: "landline",
},
error: function() {
console.log('POST Error: Landline');
},
}).done(function(data) {
// you may safely use results here
softResponse.isLandline = data;
});
$(document).ajaxStop(function () {
console.log('All AJAX Requests Have Stopped');
});
});
}
});
Sorry for the messy example as I have just been bootstrapping this up however you can see I am wrapping this focusout function:
$('#home_telephone').focusout(function () {...
Around my AJAX calls, now for some reason when I test this out on the page and un-focus on the #home_telephone element the .ajaxStop() function only runs once which is the functionality I want however if I then click on the element and un-focus again the .ajaxStop() function runs twice. Any idea why this might be happening? Thanks
Try to add e.stoppropogation() within function like:
$('#home_telephone').focusout(function (e) {
e.stopPropagation()();
//your code
});
You're adding a new ajaxStop listener every time the element is unfocused. Just move the:
$(document).ajaxStop(function () {
console.log('All AJAX Requests Have Stopped');
});
call outside of the focusout callback function.

tooltips only on first page of table

Hi i have a flexigrid to display some data on my site. Each row has a hyperlink that when the user hovers over it brings up a tool tip containing more information. However this only works for the first page on the table, when i change pages the tool tips stop working. I know this is because i use the tool tips in document.ready but i am unsure on how to solved the problem. any help would be appreciated. I've included a fiddle for the tool tips however the table does not have pagination. See fiddle ive included the code below too. This is called in document.ready
function tooltip(){
$('#tblOrder tr td a').on('mouseenter', function(event) {
var id = $('#tblOrder tr[id*="row"]').attr('id').substr(3);
$(this).qtip({
content: {
text: 'Loading.....',
ajax: {
url: '<%=Url.Action("Alarms") %>',
type: 'POST',
data: {id: id},
success: function (data, status) {
this.set('content.text', data);
},
error: function (xhr) {
console.log(xhr.responseText);
}
}
},
show: {
event: event.type,
ready: true,
effect: function () {
$(this).slideDown();
}
},
hide: {
effect: function () {
$(this).slideUp();
}
}
}, event);
});
};
When you are updating the content inside of #tblOrder you should rebind the event handler or even easier bind the mouseenter event to #tblOrder and filter the event callback with a detailed selector. So instead of your code - use this:
$('#tblOrder').on('mouseenter', 'tr td a', function(event) {

Submit Ajax Form via php without document.ready

I am submitting a number of forms on my page via php using Ajax. The code works great in forms preloaded with the page. However, I need to submit some dynamic forms that don't load with the page, they are called via other javascript functions.
Please, I need someone to help me review the code for use for forms that don't load with the page. Also the 'failure' condition is not working.
The code is below:
<script type="text/javascript">
feedbar = document.getElementById("feedbar");
jQuery(document).ready(function() {
$('#addressform').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $('#addressform').serialize(),
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
failure: function () {
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
Thanks.
You need to bind event by existing html (e.g body).
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()
see api: https://api.jquery.com/on/
Try like this:
$("body").on('submit', '#addressform',function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $('#addressform').serialize(),
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
failure: function () {
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
you can delegate to document:
$(document).on('submit', '#addressform', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $(this).serialize(), // <----serialize with "this"
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
error: function () { //<----use error function instead
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
As you have posted this line as below:
I need to submit some dynamic forms that don't load with the page
What i understand with this line is you want a common submit function for all forms which are generated dynamically, then you can do this:
$(document).on('submit', 'form', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $(this).serialize(), // <----"this" is current form context
success: function () {
//some stuff
},
error: function () { //<----use error function instead
//some stuff
}
});
e.preventDefault();
});
});
For your last comment:
You can try to get the text in ajax response like this:
success: function (data) {
feedbar.innerHTML='<div class="text-success">'+ data +'</div>';
},
error: function (xhr) { //<----use error function instead
feedbar.innerHTML='<div class="text-danger">' + xhr.responseText + '</div>';
}
if Success:
here in success function you get the response in data which is the arguement in success function, this holds the response which it requested to the serverside.
if Error:
Same way if something goes wrong at the serverside or any kind of execption has been occured then xhr which is the arguement of error function holds the responseText.
And finally i suggest you that you can place your response in feedbar selector using jQuery this way:
var $feedbar = $('#feedbar');
so in success function:
$feedbar.html('<div class="text-success">'+ data +'</div>');
so in error function:
$feedbar.html('<div class="text-success">'+ xhr.responseText +'</div>');

Categories

Resources