How to temporarily disable a button within an Ajax call? - javascript

In my Javascript code, I wrote an Ajax call where a couple of for loop cycles call two JSON files; some functions are called when some events occur and a Search button is clicked: tables containing data from the APIs requests are displayed.
I want to temporarily disable the Search button when these data are looked for within the Ajax calls, and then enable it again once the operation was carried out, in a way similar to what happens in the setTimeout() Method, but without having to set a number of milliseconds (I cannot specify it previously for the number of milliseconds depends on the slowness of the internet connection and other factors...).
How to set the .prop("disabled", false); temporarily within a callback function? In other terms, how to temporarily disable a button within an Ajax call?

You can make use of beforeSend and complete for this,
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// disable your button here
.prop("disabled", true);
},
success: function(data) {
//success
},
error: function(xhr) { // if error occured
},
complete: function() {
// enable your button here
.prop("disabled", false);
}
});

inject the object instance into the event handlers.
Checkout the possible event handlers here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
instead of Console.log call our object.prop("disabled",false") there

using JavaScript Fetch API
<!DOCTYPE html>
<html>
<body>
<div>
<button type="button" id="btn1" onclick="loadData()">Change Content</button>
<div id="response">
</div>
</div>
<script>
function loadData() {
document.getElementById("btn1").disabled = true;
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((resp) => resp.text()) // Transform the response into text
.then((data) => {
document.getElementById("response").innerHTML =
data;
document.getElementById("btn1").disabled = false;
});
}
</script>
</body>
</html>
using plain old javascript
<!DOCTYPE html>
<html>
<body>
<div>
<button type="button" id="btn1" onclick="loadData()">Change Content</button>
<div id="response">
</div>
</div>
<script>
function loadData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.status == 200) {
document.getElementById("response").innerHTML =
this.responseText;
}
document.getElementById("btn1").disabled = false;
};
xhttp.open("GET", "https://jsonplaceholder.typicode.com/todos/1", true);
xhttp.send();
document.getElementById("btn1").disabled = true;
document.getElementById("response").innerHTML = '';
}
</script>
</body>
</html>

Related

Enable and Disable the buttons

I want to enable and disable the buttons using jquery or javascript.
The real scenario is
If i click the start button it goes to the php table coloumn if the status is in running state the start button get's disabled same if the status is in stopped state the start button need to enable.
jQuery('#button-id').attr('disabled', true);
jQuery('#button-id').attr('disabled', false);
You just needs to change the disabled attribute value
Please use Ajax by JQuery.
$('#btn').click(function (e) {
e.preventDefault()
let btn = $(this)
btn_disable(btn)
$.ajax({
url: 'your_url',
method: 'your_method',
data: {your_data}, //if you haven't data please type {}
success: function (response) {
btn_enable(btn)
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
btn_enable(btn)
},
complete: function (response) {
btn_enable(btn)
}
})
})
function btn_disable(btn) {
btn.attr('disabled', 'disabled')
btn.addClass('disabled')
}
function btn_enable(btn) {
btn.removeAttr('disabled')
btn.removeClass('disabled')
}
Here you can read more about Ajax :
https://api.jquery.com/jquery.ajax/
Please check the below sample. If the API response is true then the button gets disabled and if it's false then it gets enabled
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "ur_Api, success: function(result){
if(result === true){
$("#btn_status").attr('disabled', true);
}
else {
$("#btn_status").attr('disabled', false);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button id="btn_status">Status</button>
</body>
</html>

jQuery change duplicating action

I'm stuck in a problem that seems to be very simple to solve, but I doesn't figured out. I have 3 radio each one have their data attribute for the selected payment method, but the problem is, in jQuery code I need to submit an AJAX request, based on the selected radio switch. But If I click in the first radio, give and go to 3rd radio, I get 2 POST requests. For the first radio and 3rd, when should be 1. o.O
$("#payment-form input[name=payment_option]").change(function() {
var payment_method = $("input[name=payment_option]:checked").data('payment-method');
$("#checkout-button").prop('disabled', false);
console.log(payment_method);
switch (payment_method) {
// First radio
case 'pagseguro':
$("#paypal-button").css('display', 'none');
$("#checkout-button").css('display', 'block');
$("#checkout-button").prop('disabled', false);
$checkout_button.click(function() {
$.ajax({
url: 'http://usercp.dev/doacao/fazer-doacao/pagamento/pagseguro',
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.success) {
var code = response.transaction_code
PagSeguroLightbox({
code: code
}, {
success: function(transactionCode) {
$.post("http://usercp.dev/doacao/fazer-doacao/pagamento/received", {
payment_token: response.payment_token,
payment_method: response.payment_method,
transaction_code: transactionCode,
transaction_done: response.success,
csrf_token: $('meta[name="csrf-token"]').attr('content')
})
.done(function(response) {
if (!response.success) {
toastr.error("Oops!", response.error)
}
window.location.replace(response.redirect);
}, 'json');
},
abort: function() {
toastr.options.positionClass = 'toast-top-center';
toastr.info("Você cancelou a operação de pagamento.");
$(".loader").addClass('hidden');
}
});
} else {
toastr.options.positionClass = 'toast-top-center';
toastr.error(response.error);
if (response.redirect !== "") {
window.location.replace(response.redirect);
}
}
}
});
$(".loader").removeClass('hidden');
$("#checkout-button").prop('disabled', true);
$("#checkout-button").html('<i class="fa fa-circle-o-notch fa-spin fa-fw"></i>');
});
break;
// PayPal have their one button, so work without errors.
case 'paypal':
$("#paypal-button").css('display', 'block');
$("#checkout-button").css('display', 'none');
break;
// PicPay I try to use the same button as PagSeguro (first radio)
// but as I mentioned above,
// If selected PagSeguro first and jump to PicPay I'll see to post requests (one for PagSeguro and another for PicPay). I want to fix this.
case 'picpay':
$("#paypal-button").css('display', 'none');
$("#checkout-button").css('display', 'block');
$("#checkout-button").prop('disabled', false);
$checkout_button.click(function() {
$.ajax({
url: 'http://usercp.dev/doacao/fazer-doacao/pagamento/picpay',
type: 'GET',
dataType: 'json',
success: function(response) {
if (!response.success) {
toastr.error("Oops!", response.error)
}
window.location.replace(response.redirect);
}
});
$(".loader").removeClass('hidden');
$("#checkout-button").prop('disabled', true);
$("#checkout-button").html('<i class="fa fa-circle-o-notch fa-spin fa-fw"></i>');
});
break;
}
});
HTML is simple.
<input type="radio" class="radio" name="payment_option" id="payment_option" data-payment-method="pagseguro">
<input type="radio" class="radio" name="payment_option" id="payment_option" data-payment-method="paypal">
<input type="radio" class="radio" name="payment_option" id="payment_option" data-payment-method="picpay">
So you have 2 buttons that trigger a different ajax request each, and you want to be able to trigger ajax A, then trigger ajax B and cancel ajax A.
First you must understand that Ajax is async. That means that when the ajax starts, it triggers a thread of actions separate from your main thread where all your javascript exists.
If you want to cancel A when B is triggered, or cancel B when A is triggered, you need to keep track of your ajax requests.
The simplest way I can imagine is to put your ajax inside a variable
var currentAjax = $.ajax(/* Ajax A */)
Then when you trigger a new ajax you can do something like this to get rid of the previous one
if (currentAjax) { currentAjax.abort() }
currentAjax = $.ajax(/* the new ajax you selected */)
to sum it up better
we have a variable (it could be global for simplicity's sake) that contains the last activated ajax
var currentPayAjax;
$checkout_button.click(function() {
// an inefficient but doable way to try and cancel any potential previous get
try { currentPayAjax.abort() } catch(err){}
switch (payment_method) {
case 'pagseguro':
currentPayAjax = $.ajax({/* stuff A */})
break;
case 'picpay':
currentPayAjax = $.ajax({/* stuff B */})
break;
}
)}

How to post form to two different pages with a single button click?

I have a form with a single button like below:
<form name="sampleForm" id="sampleForm" method="post" action="" enctype="multipart/form-data">
<input type="text" id="biosample" name="biosample" class="sample"/>
<input type="text" id="library" name="library" class="sample"/>
<input type="submit" name="btnAdd" id="btnAdd" class="buttonsub" value="NEXT>>">
</form>
Ajax code is:
<script>
$(document).ready(function(){
var encoded_project_id = $('#encoded_project_id').val();
$('#sampleForm').on('submit', function(){
var target = 'windowFormTarget';
window.open('', target, 'width=500,height=300');
this.setAttribute('target', target);
$.post('postdata.php', $(this).serialize(), function(){
window.location.href = 'phases.php?edit='+encoded_project_id;
}).fail(function(){
window.location.href = 'sample.php?edit='+encoded_project_id;
});
});
});
</script>
Now when button is clicked, I want to post the data from the above form in 2 pages - handler.php and postdata.php
Handler.php should open in a new javascript window and postdata.php should open in same tab and same window.
How it can be achieved?
EDIT: It would seem you are using jQuery, so change this:
$(document).ready(function () {
document.getElementById('sampleForm').onsubmit = function (e) {
var req = new XMLHttpRequest();
req.open('POST', 'test.php', true);
req.send();
}
});
to this:
$(document).ready(function(){
$('#sampleForm').on('submit', function(){
$.post('postdata.php', $(this).serialize(), function(){
console.log('success');
}).fail(function(){
console.log('error');
});
});
});
You should do two things. First add
<form target="_blank" action="handler.php"></form>
This will ensure when the submit button is clicked that the form will open a new window.
Then you need to intercept the submit like so:
document.getElementById('sampleForm').onsubmit = function(e){
//xmlHTTPRequest function
//This is where you send your form to postdata.php
}
The code above will be called first and you can send your form with the asynchronous XMLHTTPRequest object to postdata.php . After that function ends, the default behavior of the form will start and your handler.php will receive the form.
you just to need two ajax call . Do something like this
$(document).ready(function(){
// if want to stop default submission
$("#sampleForm").submit(function(e){
e.preventDefault();
});
$(document).on('click','#btnAdd',function(){
send('page1.php',{'data1':'value'});
send('page2.php',{'data1':'value'});
});
});
function send(url,data)
{
$.ajax({
url: url,
type: 'POST',
datatype: 'json',
data: data,
success: function(data) {
// success
},
error: function(data) {
alert("There may an error on uploading. Try again later");
},
});
}

Jquery AJAX to retrieve PHP variable

I have a php script that makes my page load slowly because it fetches API data from another site and parses it so I want to make it load last. I'm reading AJAX is the way to go because it is asynchronous. Below is my AJAX code so far. All I want to do at the moment is have AJAX fetch a variable from PHP and display it but I can't get it to work. I think I'm really close though.
Here is the DIV I want it to load to and the script trigger.
<div id="results"></div>
<script type="text/javascript">ajax_lastcount();</script>
Here is the AJAX script
<script type="text/javascript">
function ajax_lastcount() {
var hr = new XMLHttpRequest();
hr.open("GET", "/viewcount.php", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
var results = document.getElementById("results");
results.innerHTML = data;
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
Here is viewcount.php page
header("Content-type", "application/json");
$lastcount = "ten";
echo json_encode($lastcount);
Using jQuery this could be achieved by this code (called automatically after the page's DOM is loaded):
$(document).ready(function() {
$.ajax({
url: '/viewcount.php',
type: 'get',
dataType: 'json',
})
.success(function(data) {
$('div#results').html(data);
});
});
If you want to perform simplified GET or POST request, you can also call this instead:
$(document).ready(function() {
$.get('/viewcount.php', {'optional_params_object':'value'})
.success(function(data) {
$('div#results').html(data);
});
});
or
$(document).ready(function() {
$.post('/viewcount.php', {'optional_params_object':'value'})
.success(function(data) {
$('div#results').html(data);
});
});

javascript value is undefined from php function

This probably has some really obvious answer that I'm missing, but I just can't seem to figure it out. All the search functions from PHP and queries work. The only thing that doesn't work is that the data isn't being displayed properly in the text area translated. Below is the code.
document.getElementById("translated").innerHTML = xmlhttp.open("GET","ajax-result.php?result="+num,true);
After the innerHTML portion, whatever I add (from text to html) goes into the right place but right now the above code says it is undefined.
xmlhttp.open does not return anything - that's why you get "undefined". Read http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp , paying particular attention to
xmlhttp.onreadystatechange part.
Far more convenient way to do this is to use jquery ajax method: http://api.jquery.com/jQuery.ajax/
That's not how ajax works. You should have a callback function to be called when server responses
Something like
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
// setup callback function
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
if(xmlhttp.responseText == 1){
document.getElementById("translated").innerHTML = xmlhttp.responseText;
}
}
}
xmlhttp.open("GET",'your request to sever',true);
If you really want to save yourself some head ache, I'd familiarize yourself with jQuery.
Here is a full working example of what it appears it is you are attempting to accomplish.
The implementation of the input and button was simply to simulate the method in which a value is being specified and the function is being called.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
function runAjax(num) {
$.ajax({
'url': 'ajax-result.php',
'type': 'GET', // Can also be 'POST'
'data': {
'result': num
},
'success': function(result) {
$('#translated').html(result);
alert('success!');
},
'error': function(xhr, status, exception) {
alert('failed with status code: ' + status);
}
});
}
$(document).ready(function() {
$('button').click(function() {
var $input = $('input');
var num = $input.val();
runAjax(num);
});
});
</script>
<input type="text" name="num" value="123" />
<button type="button">Click Me!</button>
</body>
</html>

Categories

Resources