Run a event click after sucessful reload of a bootstrap table - javascript

I have this function, where I have a ajax call and in the success function, i have refresh the bootstrap table, now after the refresh i have a trigger command which i want to happen only when the refresh is done, how to do that,
success: function (result) {
console.log(result);
$('#overlay').hide();
swal({
title: result['msg'],
// text: result['text'],
type: result['type'],
showConfirmButton: true
});
$('#prospect_table').bootstrapTable('refresh');
element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click')
}
the last event click happens at its specific time but I want to run that command only when the refresh is done,ie status=200
Thanks!
I have tried:
var evnCilck = element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click'); // Or any other click function
$('#prospect_table').bootstrapTable('refresh', function(e){
evnCilck();
});
and
$('#prospect_table').bootstrapTable('refresh', function() {
element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click');
});
No help from this.

You can do it like this
$('#prospect_table').bootstrapTable('refresh', function() {
element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click');
});

Along with triggering an refresh event You also need to bind refresh eventlistener to the table like this :
var $table = $('#table');
$table.on('refresh.bs.table',function(){
// do your stuff here
element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click');
})

You can do it by this way -
var evnCilck = element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click'); // Or any other click function
$('#prospect_table').bootstrapTable('refresh', function(e){
evnCilck();
});

Related

Handling multithreadiing issue in javascript/jquery?

$(".getDetails").click(function() {
// some stuff like fetching response from server
})
when user clicks getDetails button on UI multiple times within fraction of second , jquery generates two calls for click function and my logic fails.
I think solution to this will be to disable the button on first click itself(so that use can't click multiple times). Once i get the response or just before returning
from click method i make it enable. Is there any better solution ?
If no, how can i make button disable as soon as user click button first time. I think it needs to be done before calling click method or some where in html element ?
Java provides synchronized keyword so that only one thread enters at time inside method , i am not sure is similar thing exist in javascript or not ?
Assuming the click handler executes an AJAX request you can set the button as disabled before making the request, then enable it again once the request completes. Try this:
$(".getDetails").click(function(){}
var $btn = $(this).prop('disabled', true);
$.ajax({
url: '/foo'
success: function() {
console.log('It worked!');
},
error: function() {
console.log('It failed!');
},
complete: function() {
$btn.prop('disabled', false);
}
});
});
you can try unbinding click event and after ajax call again bind click to that class
$(".getDetails").click(function(){}
$(".getDetails").unbind('click');
// some stuff like fetching response from server
)
You can use simple flag to prevent firing your logic multiple times:
var flag = true
$(".getDetails").click(function() {
if (flag) {
flag = false;
//your logic...
//when your code ends (in after-AJAX callback for example)
flag = true;
}
});
$(".getDetails").click(function(e){
var $target = $(e.currentTarget);
// assuming the click listener is on the button
$target.prop('disabled',true);
// request, stuff...and when done:
$target.prop('disabled',false);
})
try Prevent Default and return false to avoid any other event propagation
This is solution is like semaphore or monitor
var progress = false;
$(".getDetails").on('click', function(e) {
if(!progress){
progress = true;
// some stuff like fetching response from server
//also after sucessfull fetch make true to false again
}else{
console.log('something in progress');
}
e.preventDefault();
return false;
})
This should make sure that your button will not fire the async request twice, until you have a response.
function doAjaxReq() {
/*
Add your ajax operation here
as a return value of doAjaxReq
like so:
return $.ajax({
url: '/foo',
type: 'POST',
data: data
})
Since i can't use ajax here let's smilulate
it useing a promise.
*/
promise = new Promise(function(res, rej) {
setTimeout(function(){
res({foo: "bar"});
}, 1000)
})
return promise;
}
/*
Inside here you add the click handlder
only once use `elem.one('click'...`
*/
function addClickHandler(elem) {
elem.one('click', function() {
// do your ajax request and when its
// done run `addClickHanlder` again
// i'm using `.then` because of the promise,
// you should be using `.done`.
doAjaxReq().then(function(data) {
console.log(data);
addClickHandler(elem);
});
})
}
addClickHandler($(".getDetails"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="getDetails">Get Details</button>

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.

JQuery Prevent Function .click Firing On Every Click

When I click a chat on my site I want the messages to be grabbed from the server so I use an $.post request like so :
$("#friendsDiv").on("click", "#aFriend", function(event){
retrieveMessages();
}
and this is what is in the retrieveMessages function
$.post("PHP/chat.php",
{
action:'retrieveMessages',
last_message: last_message,
conversation_id:conversation_id
},
function(data){
$("#messages").append(data);
last_message = $("#messages").find(".aMessage:last").attr("id");
$("#messages").animate({ scrollTop: $("#messages")[0].scrollHeight}, 1000);
}
);
The issue is that if the button is clicked very quickly multiple post requests will begin before the last_message is updated, this results in many copies of the same messages being displayed. Is there a way to prevent the button being clicked quickly or stop the post request being processed if another of the same request is already being processed?
EDIT
The #aFreind element is a DIV not a button
Typically in such situation you just disable a button until request is complete. For this you will need to provide a callback function. For example:
$("#friendsDiv").on("click", "#aFriend", function (event) {
// reference the button
var button = this;
// disable the button
this.disabled = true;
// provide a callback to be invoked when post is done
retrieveMessages(function() {
button.disabled = false;
});
});
function retrieveMessages(callback) {
$.post("PHP/chat.php", {
action: 'retrieveMessages',
last_message: last_message,
conversation_id: conversation_id
}, function (data) {
$("#messages").append(data);
last_message = $("#messages").find(".aMessage:last").attr("id");
$("#messages").animate({
scrollTop: $("#messages")[0].scrollHeight
}, 1000);
// execute callback which enables button again
callback();
});
}
Demo: http://jsfiddle.net/9t8fLdjn/
Your best bet would be to disable the button and then enable it after $.post
$("#friendsDiv").on("click", "#aFriend", function(event) {
$(this).prop('disabled', true); // disable
retrieveMessages();
});
and the retrieveMessage function
$.post("PHP/chat.php", {
action: 'retrieveMessages',
last_message: last_message,
conversation_id: conversation_id
}, function(data) {
$("#messages").append(data);
last_message = $("#messages").find(".aMessage:last").attr("id");
$("#messages").animate({
scrollTop: $("#messages")[0].scrollHeight
}, 1000);
$(this).prop('disabled', false); // enable it again
});
Instead of using on you could use the one jQuery function and bind the button again in the callback. Se http://api.jquery.com/one/
$("#friendsDiv").one("click", "#aFriend", retrieveMessages });
var retrieveMessages = function(){
$.post("PHP/chat.php", {
...
}).done(function(){
$("#friendsDiv").one("click", "#aFriend", retrieveMessages });
});
};

jquery mobile - pageinit event no triggered when using mobile.changePage

I have the following code for handling on click event of a button:
$(document).on("click", '.submit_review_button', function(event, ui) {
var place = $.data(this, "object");
var ttext = $("#review_text").val();
var review = new Object();
review.business_place_id = place._id;
review.review = ttext;
review.user_id = user._id;
// var review = {business_place_id:place.id, review: ttext, user_id: user.id}
$.ajax({
url: site_url + '/reviews/',
type:'POST',
data: review,
success: function(data) {
$.mobile.changePage("show_reviews_page", {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
});
// initShowReviewsPage();
},
error:function(data) {
alert(1);
}
});
});
I also have this code in document-ready:
$("#show_reviews_page").on('pageinit', function() {
initShowReviewsPage();
});
I know that the pageInit binding works, because if I go to #show_reviews_page using it works.
But when clicking on the .submit_review_button button, the on click event fires, the page changes but the init doent fire and the page is not valid.
Any idea why it doesnt work?
"pageinit" event is fired only once when the page loads in the DOM for the first time.
If you want fire a function everytime you go to a page, use "pageshow" or "pagebeforeshow" events.

Show loading animation when collapsible block is opening Jquery Mobile

I have a problem trying to show loading icon when collapsible block is opening. I have a collapsible block with a listview inside which is populated dynamically via ajax/php. They list might have up to 500 elements, so I would like to show loading animation while it is loading.
I have tried
$('div.century').live('expand', function(){
var idval = $(this).attr('id');
console.log('expanded'+idval);
$.mobile.showPageLoadingMsg ();
$.get("helpers/getByCentury.php", { id: idval},
function(data){
$("#"+idval+" ul.ulist").html(data);
$("#"+idval+" ul.ulist").listview('refresh');
});
$.mobile.hidePageLoadingMsg ();
});
I have also tried
$('div.century').live('expand', function(){
var idval = $(this).attr('id');
console.log('expanded'+idval);
$.mobile.pageLoading();
$.get("helpers/getByCentury.php", { id: idval},
function(data){
$("#"+idval+" ul.ulist").html(data);
$("#"+idval+" ul.ulist").listview('refresh');
});
$.mobile.pageLoading(true);
});
without any luck.
Can anyone tell me how to fix this?
Thanks in advance.
You want to call $.mobile.hidePageLoadingMsg() in the callback function for your ajax call:
$('div.century').live('expand', function(){
var idval = $(this).attr('id');
console.log('expanded'+idval);
$.mobile.showPageLoadingMsg ();
$.get("helpers/getByCentury.php", { id: idval},
function(data){
$("#"+idval+" ul.ulist").html(data);
$("#"+idval+" ul.ulist").listview('refresh');
$.mobile.hidePageLoadingMsg ();//NOTICE: this has been moved inside the callback function for your $.get() call
});
});
Also a couple pointers.
You are using the $("#"+idval+" ul.ulist") selector twice in a row, you can make that more efficient by chaining function calls together like so:
$("#"+idval+" ul.ulist").html(data).listview('refresh');
If other people view your webpage in a browser that does not have the console.log function they will get an error and your JS will stop running, it is normally a good idea to put calls to the console.log function inside a conditional that checks for the existance of that function:
if (typeof(console.log) == 'function') {
console.log('expanded'+idval);
}

Categories

Resources