Disable 2 buttons after click of a button - javascript

I have a submit button on page index.php When i click this button another script (call.php) is called through ajax that holds some response. Now i want that time between the click of submit button and response displayed/received under a div through the call of ajax script the buttons option1 and option2 should get disabled. and when succesfully the result is dispalyed the 2 buttons should get enabled, however i am not able to do so. can anyone help me with it
3 buttons and script code on index.php page is
<button class="rightbtn" type="button" id="submitamt" style="display:none; ">Submit</button>
<button class="botleftbtn" type="button" id="walkaway" style="display:none">Option1</button>
<button class="botrightbtn" type="button">Option2</button>
<script>
function myFunction() {
alert("You need to login before negotiating! However you can purchase the product without negotiating");
}
var startClock;
var submitamt;
var walkaway;
var digits;
$(function() {
startClock = $('#startClock').on('click', onStart);
submitamt = $('#submitamt').on('click', onSubmit);
walkaway = $('#walkaway').on('click', onWalkAway);
digits = $('#count span');
beforeStart();
});
var onStart = function(e) {
startClock.fadeOut(function() {
startTimer();
submitamt.fadeIn(function() {
submitamt.trigger('click'); // fire click event on submit
});
walkaway.fadeIn();
});
};
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'call.php',
dataType: 'json',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
var onWalkAway = function(e) {
//console.log('onWalkAway ...');
};
var counter;
var timer;
var startTimer = function() {
counter = 120;
timer = null;
timer = setInterval(ticker, 1000);
};
var beforeStart = function() {
digits.eq(0).text('2');
digits.eq(2).text('0');
digits.eq(3).text('0');
};
var ticker = function() {
counter--;
var t = (counter / 60) | 0; // it is round off
digits.eq(0).text(t);
t = ((counter % 60) / 10) | 0;
digits.eq(2).text(t);
t = (counter % 60) % 10;
digits.eq(3).text(t);
if (!counter) {
clearInterval(timer);
alert('Time out !');
resetView();
}
};
var resetView = function() {
walkaway.fadeOut();
submitamt.fadeOut(function() {
beforeStart();
startClock.fadeIn();
});
};
</script>

You can achieve this by disabling the buttons before you make the AJAX request, and then enabling them again in the complete handler of the request. Try this:
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$('.botleftbtn, .botrightbtn').prop('disabled', true); // < disable the buttons
$.ajax({
type: 'post',
url: 'call.php',
dataType: 'json',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
},
error: function() {
console.error('Failed to process ajax !');
},
complete: function() {
$('.botleftbtn, .botrightbtn').prop('disabled', false); // < enable the buttons
}
});
};
Note that its best to enable the buttons in the complete handler and not the success handler. This is because if there is an error the buttons will never be enabled again.

Disable the buttons on click, and enable them on ajax success:
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
//Disable buttons ---------------------- //
//Give an id to the second button
$('#walkaway, #the_other_button').prop('disabled', true);
$.ajax({
type: 'post',
url: 'call.php',
dataType: 'json',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
//Enable buttons ---------------------- //
$('#walkaway, #the_other_button').prop('disabled', false);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};

In your onsubmit() code, get a var reference to the buttons you wish to deactivate
Var btn1 = document.getElementbyId("btn1");
But you would have to set an Id for the two buttons.
You can disable these in your submit code and then enable them when your timer is done.
Btn1.disabled = true;
When your timer is done, set it as false the same way.

Related

if/else with setInterval auto-refreshing and on click refreshing event jquery?

Struggling to get this to work properly...Making an if/else statement with setInterval that if class is clicked, content refreshes, else content auto refreshes after a specific time period. This is what I have for just auto refreshing atm (which works perfectly):
var auto_refreshContentTwo = setInterval (
function() {
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
}, 495000
);
What I've tried to get a "click" function added, but doesn't do anything...:
$('.contentTwoClicked').on('click', function() {
var refreshClicked = true;
if(refreshClicked) {
alert('clicked');
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
} else {
var auto_refreshContentTwo = setInterval (
function() {
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
}, 495000
);
}
});
Where am I going wrong? Or am I way off-base here...? Any guidance/help would be greatly appreciated!
You don't need a conditional statement, but rather a variable to store the set interval in so that it can be cleared and restarted on manual refresh via a calling function:
//variable to store the setInterval
let refreshInterval = '';
//function that calls setInterval
const autoRefresh = () => {
refreshInterval = setInterval(()=> {
refresh();
console.log("auto");
},3000)
}
//run setInterval function on page load;
autoRefresh();
//manual refresh function
const manualRefresh = () => {
//erases the setInterval variable
clearInterval(refreshInterval);
refresh();
//then recalls it to reset the countdown
autoRefresh();
console.log("manual");
}
//for visual purposes
let refreshCount = 0;
//node refresher function
const refresh = () => {
const container = document.getElementById("refresh");
refreshCount ++;
container.textContent= "This div will be refreshed"+ ` Refresh Count: ${refreshCount}`;
}
<button onclick="manualRefresh()">Click to Refresh </button>
<div id="refresh">This div will be refreshed</div>
See it in action: https://codepen.io/PavlosKaralis/pen/rNxzZjj?editors=1111
Edit: Applied to your code I think it would be:
let interval;
var autoRefresh = () => {
interval = setInterval (
function() {
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
}, 495000);
}
$('.contentTwoClicked').on('click', function() {
clearInterval(interval);
alert('clicked');
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
autoRefresh();
});
autoRefresh();

setTimeout function didn't work in if else condition - Jquery

I have code like this:
var saveToDB;
if ($('.new_article')[0]) {
saveToDB = function() {
var form;
form = $('.new_article');
$.ajax({
url: '/admin/articles',
type: 'POST',
data: form.serialize(),
beforeSend: function(xhr) {
$('.form-status-holder').html('Saving...');
},
success: function(data) {
var jqObj;
jqObj = jQuery(data);
$('.form-status-holder').delay(5000).hide();
}
});
};
$('form input, form textarea').on('input propertychange change', function() {
var timeoutId;
clearTimeout(timeoutId);
return timeoutId = setTimeout((function() {
saveToDB();
}), 5000);
});
return;
} else if ($('.edit_article')[0]) {
saveToDB = function() {
var form, id;
form = $('.edit_article');
id = (form.attr('action')).split("/").pop(-1);
$.ajax({
url: '/admin/articles/' + id,
type: 'POST',
data: form.serialize(),
beforeSend: function(xhr) {
$('.form-status-holder').html('Saving...');
},
success: function(data) {
var jqObj;
jqObj = jQuery(data);
$('.form-status-holder').delay(5000).hide();
}
});
};
$('form input, form textarea').on('input propertychange change', function() {
var timeoutId;
clearTimeout(timeoutId);
return timeoutId = setTimeout((function() {
saveToDB();
}), 5000);
});
return;
}
I got problem with setTimeout function in if condition while it cannot call to saveToDB inside. It takes me hours to find where is the problem come from but now I still get stuck. The second setTimeout function in else condition works correctly. Any help? Thanks in advance.

Firing a function every x seconds

I am currently using a keyup function to initiate my autosave.php file which auto saves information to a table. However, I am starting to find that the keyup seems to be inefficient due to fast typing and submitting long strings.
How can I have the ajax submit every x seconds, instead of each keyup after so many ms?
$(document).ready(function()
{
// Handle Auto Save
$('.autosaveEdit').keyup(function() {
delay(function() {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 500 );
});
});
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Solution
Use setInterval It is like setTimeout but repeats itself.
setInterval(function () {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 1000);
Optimization
turn it on when the control has focus and turn it off when focus leaves. Also poll for the form data if it has updated then send the ajax request otherwise ignore it.
var saveToken;
var save = (function () {
var form;
return function () {
var form2 = $('#ajaxForm').serialize();
if (form !== form2) { // the form has updated
form = form2;
$.ajax({
type: "post",
url: "autosave.php",
data: form,
success: function(data) {
console.log('success!');
}
});
}
}
}());
$('.autosaveEdit').focus(function() {
saveToken = setInterval(save, 1000);
});
$('.autosaveEdit').focusout(function() {
clearInterval(saveToken);
save(); // one last time
});
I believe that what you are looking for is the window.setInterval function. It's used like this:
setInterval(function() { console.log('3 seconds later!'); }, 3000);
Use setInterval
function goSaveIt()
{
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}
setInterval(goSaveIt, 5000); // 5000 for every 5 seconds

Adding Gritter Message After Second Deletion

I'm trying to find out why when a user is deleted by clicking on the ajax-delete class icon and performs the deletion process it shows the gritter message after deletion however if you were to immediately delete another user afterwards it removes the previous gritter message but doesn't show another for that second deletion. Any ideas on why this could be?
EDIT: I have figured out that the issue belongs to the $.gritter.removeAll(); code line. When there is another existing notification it removes it but doesn't add the next notification.
Any ideas what I should do here?
var rowToDelete = null;
var basicTable = null;
var api_url = null;
$(document).ready(function() {});
$(document).on('click', '.ajax-delete', function(e)
{
console.log(basicTable);
e.preventDefault();
//defining it like this captures and optimizing the need to cycle over the DOM more than once
//in subsequent calls to the element specifically
$elem = $(this);
$parentElem = $elem.closest('tr');
rowToDelete = $parentElem.get(0);
api_url = $elem.attr('href');
runConfirmation($('td:eq(1)', $parentElem).text());
});
function runConfirmation(nameSting)
{
$mymodal = $('#myModal');
$('.modal-body p', $mymodal).html('Are you sure you want to delete this <strong>'+nameSting+'</strong>?');
$mymodal.modal('show');
}
$('#myModalConfirm').on('click', function(e) {
$.ajax({
type: 'post',
url: api_url,
data: { _method: 'DELETE' },
dataType: 'json',
success: function(response) {
$.gritter.removeAll();
var className = 'growl-danger';
if (response.status == "SUCCESS") {
className = 'growl-success';
basicTable.fnDeleteRow(basicTable.fnGetPosition(rowToDelete));
rowToDelete = null;
api_url = null;
}
$.gritter.add({
position: 'top-right',
fade_in_speed: 'medium',
fade_out_speed: 2000,
time: 6000,
title: response.title,
text: response.message,
class_name: className,
sticky: false
});
}
});
$('#myModal').modal('hide');
});
Replace the following line:
$.gritter.removeAll();
With
$('.gritter-item-wrapper').remove();

How to prevent duplicated AJAX call?

I'm currently building a simple AJAX call application which will show the result of a textbox after typing some texts inside it:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$(document).ready(function(e) {
$("input[name=html]").keyup(function(e) {
if(this.value.length > 1) {
e.preventDefault();
var form = $(this).closest('form');
var form_data = form.serialize();
var form_url = form.attr("action");
var form_method = form.attr("method").toUpperCase();
delay(function(){
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#result").html(returnhtml);
$("#loadingimg").hide();
}
});
},1000);
}
});
});
Fiddle Demo
As you can see from the demo above, for instance if you type test,test1 or test2 or any word as long as their length is longer than one then it'll make an AJAX call.
My question is that is there any way that allow me to prevent duplicate AJAX call? For example if I type test in the textbox again, it'll immediately show test in the div without making another AJAX call to fetch the result again. Thank you very much in advance.
You just need to cache previous results and, before making the ajax call, check the cache to see if you already have that result in the cache.
In Javascript, one usually uses an object for a cache:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
// create cache for ajax results
// the key is the form_data
// the value is whatever the ajax call returns
var ajaxCache = {};
$(document).ready(function(e) {
$("input[name=html]").keyup(function(e) {
if(this.value.length > 1) {
e.preventDefault();
var form = $(this).closest('form');
var form_data = form.serialize();
// check the cache for a previously cached result
if (ajaxCache[form_data]) {
// this uses delay, only so that it clears any previous timer
delay(function() {
$("#result").html(ajaxCache[form_data]);
$("#loadingimg").hide();
}, 1);
} else {
var form_url = form.attr("action");
var form_method = form.attr("method").toUpperCase();
delay(function(){
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#result").html(returnhtml);
// put this result in the cache
ajaxCache[form_data] = returnhtml;
$("#loadingimg").hide();
}
});
},1000);
}
}
});
});
Working demo: http://jsfiddle.net/jfriend00/P2WRk/

Categories