JQuery & Ajax disable click - javascript

I have a table with data and a function to help me get values from rows:
function getRow () {
$('#mytable').find('tr').click( function(){
let fname = $(this).find('td:eq(4)').text();
let start = $(this).find('td:eq(5)').text();
let end = $(this).find('td:eq(6)').text();
.......ajax method () etc
................
}
So far, it has been working perfectly and fetching me the correct data. I had another function elsewhere in the page, where clicking on some links would fetch some data from the server and reload the page to display the new data. Everything was working like clockwork.
Now, I decided that when re-displaying fresh data, instead of reloading the page, it's better to refresh the #mytable div. Indeed, it worked, but alas it spoiled the first function. So basically the function below has introduced a bug elsewhere in the page, and I'm not sure why or how to fix it. It's as if the div refresh has completely disabled the event handler. Any ideas?
$(document).ready(function() {
$(".key").click(function(event) {
event.preventDefault();
var word = event.target.innerHTML;
$.ajax({
url: '.../',
data: {
action : "key",
keyword: word
},
type: 'get',
success: function(data){
$('#mytable').load("/.../../..." + ' #ytable');
},
error: function(e){
console.log(e);}
});
});
});

Related

Reload part of the page Jquery

I have a table with a td that updates when i press a button .pauseDocker
When It's paused I'm reloading the page. Surely there's a smarter way to just refresh just part of the page in this case the table.
$(document).on('click','.pauseDocker' ,function(){
var buttonClicked = $(this);
var containerName = $(this).attr('name');
$.ajax({
type: 'post',
url: '/container/pause',
data: {containerName: containerName},
success: function () {
location.reload();
},
error: function() {
}
});
});
You can get the first parameter of the success callback and this will contain data from the response of your server. Use that to retrieve the changed data and update client side accordingly

Jquery Function running multiple times

I am using two scripts on my page and there is a general click function which records the number of clicks one user is making. So when I click on any element in the document, the click function should run after which other functions on the same element runs. But in my case, the click function runs multiple times before passing the control to the other function.
/************ 1st Jquery Script ***************/
function($) {
$(function(e) {
$('.signupCustom').click(function(){
var email = $('#form-email').val()
var password = $('#pass').val()
var firstName= $('#form-first-name').val()
var lastName= $('#form-last-name').val()
var number= $('#form-mobile').val()
var type=$('#sel1').val()
$.ajax({
url: '/login',
type: 'GET',
data: {
'email': email,
'password':password,
'firstName':firstName,
'lastName':lastName,
'number':number,
'type':type
},
success: function(data){
if ($('#sel1').val() == "Travel-Agent"){
window.location.href = "/agentVerification.html"
}
else{
window.location.href = "/dashboardTraveller"
}
}
})
})
$('.login').click(function(){
var email = $('#form-username').val()
var password= $('#form-password').val()
$.ajax({
url: '/loginCustom',
type: 'GET',
data: {
'email': email,
'password':password
},
success: function(data){
window.location.href = data['url']
}
})
})
$('.destinationsButton').click(function(){
var url="/destinations";
window.location=url;
})
}); })(jQuery);
I have attached the link to the html page which contains the second script.
Link to Page
If you go to this link, there is an image:
When I click on Login button, the click function runs multiple times before control goes to other function. I want the click function to run single time and then control should go to other function.
I tried e.stopPropagation but in case of a popup on same page, the popup does not open. Here on clicking on login, popup comes.
Is there any reason you are using the below?
jQuery('*').on("click",function(e){});
I think this might work better
jQuery('body').on("click",function(e){});
good luck
I don't know where you're stuck but you may use one to run the click function just once:
$(selector).one('click',function(){
//code runs only one click
});

jQuery .on not working after ajax delete and div refresh

On a page with a tab control, each tab contains a table, each tr contains a td with a button which has a value assigned to it.
<td>
<button type="button" class="btn" name="deleteEventBtn" value="1">Delete</button>
</td>
This code below works for the first delete. After the AJAX call & the refresh of the div, no further delete buttons can be clicked. The .on is attached to the document. The same happens if I attach it to the body or anything closer to the buttons.
function deleteRecord(url, id, container) {
$.ajax({
type: "POST",
url: url,
data: { id: id },
success: function (data) {
$('#delete-popup').hide();
$(container).trigger('refresh');
}
});
}
$(document).ready(function () {
$(document).on('click', '[name^="delete"]', function (e) {
e.preventDefault();
var id = $(this).val();
$('#current-record-id').val(id);
$('#delete-popup').modal('show');
});
$('#delete-btn-yes').on('click', function (e) {
e.preventDefault();
var recordId = $('#current-record-id').val();
var recordType = location.hash;
switch (recordType) {
case "#personList":
deleteRecord(url, recordId, recordType);
break;
}
});
});
Any ideas? Could it be related to the wildcard for starts with [name^="delete"]? There are no other elements where the name starts with 'delete'.
EDIT
When replacing
$(container).trigger('refresh');
with
location.reload();
it "works", however that refreshes the whole page, loses the users position and defeats the point of using AJAX.
As the button click is firing at first attempt, there is no issue in that code. All you have to do is, put the button click event in a method and call it after the refresh. This way, the events will be attached to the element again. See the code below,
function deleteRecord(url, id, container) {
$.ajax({
type: "POST",
url: url,
data: { id: id },
success: function (data) {
$('#delete-popup').hide();
$(container).trigger('refresh');
BindEvents();
}
});
}
$(document).ready(function () {
BindEvents();
});
function BindEvents()
{
$(document).on('click', '[name^="delete"]', function (e) {
e.preventDefault();
var id = $(this).val();
$('#current-record-id').val(id);
$('#delete-popup').modal('show');
});
$('#delete-btn-yes').on('click', function (e) {
e.preventDefault();
var recordId = $('#current-record-id').val();
var recordType = location.hash;
switch (recordType) {
case "#personList":
deleteRecord(url, recordId, recordType);
break;
});
}
Apologies to all and thanks for your answers. The problem was due to the way the popup was being shown & hidden.
$('#delete-popup').modal('show');
and
$('#delete-popup').hide();
When I changed this line to:
$('#delete-popup').modal('hide');
it worked. Thanks to LShetty, the alert (in the right place) did help!
If you are using Bootstrap Modal
After Ajax Request before Refreshing page add
$('.modal').modal('hide');
This Line will Close your Modal and reload your page. Before that it will complete all Ajax Request things.
But for google chrome there is no issues :) hope this help someone.

Prevent previously requests on click

I have list of tables,
<table id="<%#DataBinder.Eval(Container.DataItem, "Certificate")%>" class="tbl_evenSearchResultRow" onmouseover="this.className='ResultGridRowSeleted'" onmouseout="this.className='tbl_evenSearchResultRow'" onclick="return SynopsisWindowOpen(this)">
onclick of each i use next function:
function SynopsisWindowOpen(obj) {
var title = $(obj).find("strong[name='title']").html();
var isParentools = 0;
if (window.location.href.indexOf('recent_releases.aspx') > -1)
isParentools = 1;
var url = "/ratings/Synopsis.aspx?logoonly=1&Certificate=" + obj.id + "&Title=" + encodeURIComponent(title) + "&parentools=" + isParentools;
$("#ratingModal").on("show.bs.modal", function (e) {
$.ajax({
url: url,
cache: false,
dataType: "html",
success: function (data) {
$("#ratingModal").find(".modal-body").html(data);
}
});
});
$("#ratingModal").on("hide.bs.modal", function (e) {
$(this).find(".modal-body").html('');
});
$("#ratingModal").modal('show');
return false;
}
By url i render body of modal : i get certificate from request.query and according to it render body
LoadSynopsisContent(Request.QueryString["Certificate"], Request.QueryString["parentools"]);
Problem : when i click at first - everything seems to be good, on second click in modal body firstly rendered body of first click and then of second click. And so on.
I don't know where is problem.
Firstly i use jquery load function, but then i change to simple ajax call with disabled caching.
Move the all event bindings to outside of the function and everything should work fine.
Thus, these parts should not be inside the function:
$("#ratingModal").on("show.bs.modal", ....);
$("#ratingModal").on("hide.bs.modal", ....);
Here is one way you could organize your code:
var url; //a global variable ... not a good idea though
function SynopsisWindowOpen(obj) {
....
url = .....
}
$(function() {
$("#ratingModal").on("show.bs.modal", ....);
$("#ratingModal").on("hide.bs.modal", ....);
});
However, the way would be to not use inline JavaScript but to take advantage of the power of jQuery to separate structure from behavior.
UPDATE
Instead of using a global variable url you can store the new url in a data attribute of the modal. Then you can get it from there when the modal opens.
In the function:
//calculate the url
var url = .....
//store the url in the modal
$('#ratingModal").data('table-url', url);
In the modal event handler:
$("#ratingModal").on("show.bs.modal", function(e) {
//retrieve the url from the modal
var url = $(this).data('table-url');
//use the url
$.ajax({ url: url, .... }):
});

Appending item to list with Ajax after post - layout related

I have an activity stream for both users use, and site-wide view. Currently when a user posts an update, I have it displaying a default bootstrap success alert. I have seen other websites append the new post to the list by sliding down the existing items, and appending the newest post to the top of the list.
I am attempting to do just that, but I am not sure how to add it with all the proper styling. (code below). I am tried adding all the <div> tags that make up one activity item in my feed, but without success.
TL;DR - Is there a way to have ajax look at the current top activity item, clone it, and append it to the top? It would make the code more dynamic for my use, and avoid having to place CSS inside the .js file.
jQuery(document).ready(function ($) {
$('form#postActivity').submit(function (event) {
event.preventDefault();
$postActivityNow = (this);
var subject = $('#activity_subject').val();
var message = $('#activity_content').val();
var data = {
'action': 'postAnActivity',
'subject': subject,
'message': message,
}
$.ajax({
type: 'post',
url: postAnActivityAjax.ajaxurl,
data: data,
error: function (response, status) {
alert(response);
},
success: function (response) {
if (response.success) {
bootstrap_alert.success('Activity Added');
} else {
if (response.data.loggedIn == false) {
bootstrap_alert.warning('you are NOT logged in');
console.log('you are not logged in')
}
if (response.data.userExists == false) {
console.log(response);
bootstrap_alert.warning(response.data.alertMsg);
console.log(response.data.alertMsg)
}
}
}
});
});
});
you can also use .prependTo()
var newActivity = $( ".activity" ).first().clone();
newActivity.prependTo( ".parentDiv").hide().slideDown();
FIDDLE
To clone an element: jQuery.clone()
var newItem = $("#myDiv").clone();
To append it as first child: jQuery.prepend()
$("#parentDiv").prepend( newItem );
Regards,
hotzu
I have already done in the past using $.prepend()
Check this url for more information jquery append to front/top of list

Categories

Resources