how do make waiting for ajax to complete - javascript

I newbie.
I have a function application for employment (apply-job).What I do is submit the request with an ordinary link, with a click-function applied on it but processing time is quite long. I want disable "#apply-job" avoid click too much or disable window and fade for ajax to complete. Thank.
My JS:
$("#apply-job").click(function() {
if($('#jobcandidate-name').val() != '' && $('#jobcandidate-email').val() != '' && $('#jobcandidate-phone').val().length >= 10 && $('#jobcandidate-address').val() != '' && ($("input[name='CandidateAttachment[2][fileAttachment][path]']").val() != undefined || $('#jobcandidate-curriculum_vitae').val() != '') ){
let data = $('#apply-job-form').serialize();
let roleArticle = $('.show_new_role :input').serialize();
if ($('#apply-job-form').find('.has-error').length){
swal("Thử lại", "Vui lòng kiểm tra lại thông tin!", "error");
} else {
$.ajax({
url: '$urlRequest',
type: 'POST',
dataType: 'html',
data : data + '&' + roleArticle
}).done(function(result) {
response = JSON.parse(result);
if (response.type == "success"){
let checkReload = swal("Thành công", "Cảm ơn bạn đã ứng tuyển!", "success");
checkReload.then(function() {
location.reload();
});
}
});
}
} else {
if ($("input[name='CandidateAttachment[2][fileAttachment][path]']").val() == undefined && $('#jobcandidate-curriculum_vitae').val() == '') {
$('#jobcandidate-curriculum_vitae').parents('.form-group').find('.txt-lable').css('color','red');
$('#jobcandidate-curriculum_vitae').parents('.form-group').find('.show_error2').text('* Không được bỏ trống');
}
swal("Thử lại", "Vui lòng kiểm tra lại thông tin!", "error");
}
});

ajax has await option. You can use it to make the execution wait till the ajax all is done. Make sure you combine it with async which will tell there's an asynchronous step in the function. See below snippet
$("#apply-job").click(async function() {
......
await $.ajax({
......
});
Update: to make sure the click is disabled while ajax is working, add a disabled attribute and assign the click only when the attribute is not present. Clear the attribute once process is complete.
$("#apply-job:not([disabled])").click(async function() {
$("#apply-job").attr("disabled","disabled")
......
await $.ajax({
......
$("#apply-job").remoeAttr("disabled")
});

Related

jQuery prevent submit of form inside of if statement

Sorry if there are some mistakes, but I am a total noob and I am also posting for the first time on StackOverflow.
I am trying to configure a submit form, that controls if the inserted PIN is right, and if so goes on with the submission. I did some online research and found out that with jQuery we can use to function event.preventDefault(), I tried to insert it inside my AJAX request but it looks like it doesn't stop the form from being saved.
The code looks like these:
function verifyOTP() {
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp" : otp,
"PIN" : PIN,
"action" : "verify_otp"
};
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
},
error : function() {
alert("ss");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
error : function(event) { event.preventDefault(); };
}
//if I insert "return false;" here the submit is always blocked
}
I checked on atom if the parenthesis are right and it looks like it is.
Any ideas how I should use the preventDefault()?
I also checked if the output of m_ajaxpinr.php is correct, and it is. I also tried like these but it still didn't work...
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
$("form").submit(function(event) {
if (response.type == 'success')
{
alert(response.type);
}
else if (response.type == 'error')
{
alert(response.type);
event.preventDefault();
}
});
as said in comment above ajax call is asynchronous, you need to complete cancel default action for the form or put event.preventDefault(); on the top function, then submit it in success function if it valid otp.
.val() will not return null, it return empty if no input.
$('#myForm').on('submit', verifyOTP);
function verifyOTP(e) {
e.preventDefault(); // note this
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp": otp,
"PIN": PIN,
"action": "verify_otp"
};
if (otp) { // mean not null, undefined, empty, false, 0
$.ajax({
//url: 'm_ajaxpinr.php',
url: 'https://httpbin.org/anything/test',
type: 'GET',
dataType: "json",
data: input,
success: function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
if(response.args.otp == 1234){
console.log('valid otp, continue submission')
$('#myForm').off('submit'); // remove submit event
$('#myForm').submit(); // then submit the form
}
else{
console.log('invalid pin,\nvalid pin: 1234');
}
},
error: function() {
console.log("server error, submission cancelled");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
console.log("otp maybe empty, submission cancelled");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<input id="contomovimentato">
<button>submit</button>
</form>

Show alert after reloading page

I have tried this function but it displays the alert then refreshes the form. I want something that refreshes the page and then displays the alert. How can I do that?
$(document).on('click', '#insert', function(){
var address = $('#to_address').val();
var amount = $('#amount').val();
var this_email = $('#this_email').val();
var this_bal = $('#this_bal').val();
if(address != '' && amount != '' && this_email != '' && this_bal != '' )
{
$.ajax({
url:"WithdrawChk.php",
method:"POST",
data:{address:address, amount:amount, this_email:this_email, this_bal:this_bal},
success:function(data)
{
$('#alert_message').html('<div class="alert-success">'+data+'</div>');
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
else
{
alert("All Fields are required");
}
});
You can do something like this
success: function(data) {
window.sessionStorage.setItem("successData" , JSON.stringify(data));
window.location.reload();
}
$(document).ready(function(){
if(window.sessionStorage.getItem("successData")){
$('#alert_message').html('<div class="alert-success">' + JSON.parse(window.sessionStorage.getItem("successData")) + '</div>');
}
})
Make sure to clear the session storage before the ajax call. And you can store only string values in the local or session storage so you have to stringify the json object to store it in session storage , and then if you want to use it , you have to parse that.
As per Rorys suggestion you can store the data in localStorage and check for if it exists on the jQuery page ready function.
var localStorage = window.localStorage;
$(function(){
var data = localStorage.getItem("data");
if(data !== null){
$('#alert_message').html('<div class="alert-success">' + JSON.parse(data) + '</div>');
localStorage.removeItem("data");
}
});
success: function(data) {
localStorage.setItem("data", JSON.stringify(data);
window.location.reload();
}

Run Function If user delete the word

So I have a jQuery code for sending keywords to another page.On that page I have names of all countries. my code works good also, I have defined my function in a condition that if the lenght of text of input was longer than 2 then runs the function inside it but, I have problem with this for Example when I write the city name it works good and returns the correct data from the ajax page my issue is when the user wants to delete that word with backspace or somthing else I want to remove all previous data was sent to ajax page but because of my condition it does not work.
how can I define if user delete the word run my function ?
here is my code :
var prevXHR = null; //global
$('.country').each(function() {
$(this).on('keyup', function(e) {
var _this = this;
var element = $(this).val().length;
if (e.which !== 0 &&
!e.ctrlKey && !e.metaKey && !e.altKey
){
if (element > 2) {
var val = $(this).val()
$(this).val(val)
prevXHR = $.ajax({
url: "ajaxpage.htm",
type: "get",
contentType: 'application/json; charset=utf-8',
data: {
key: $(this).val()
},
success: function(result) {
$(_this).closest(".search_div").find(".co").empty().html(result)
},
beforeSend: function(){
if(prevXHR && prevXHR.readyState != 20){
//before sending any new request neutralize any pending ajax call
prevXHR.abort();
prevXHR = null;
}
}
});
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="search_div">
<input type="text" value="" class="country" autocomplete="off" />
<div class="result"></div>
</div>
In your code, you are already checking to see if the length of the input was greater than 2, then proceeding with ajax call.
Just add else part afterwards.
if (element > 2) {
// ...do the ajax stuff here
} else {
// the input length was shorter than 2 characters...
// remove all HTML elements here
$('div#to_be_removed').remove(); //or something like that
}

Refreshing the thankyou message on the form page after submitting

I have a simple form in a page.The form is submitting to the same page and displaying the thank you message there it self. But the issue is that i want to remove the thank you message after some seconds or refresh the page. Is there any solution.
Here is the script:
<script>
/* ==============================================
Ajax Submiting For Email Subscriber Form.
=====================================================================*/
$("#subscriber_form").submit(function(e) {
$('#show_subscriber_msg').html('<div class=gen>Submiting..</div>');
var subscriberemail = $('#subscriberemail').val();
var formURL = $(this).attr("action");
var data = {
subscriberemail: subscriberemail
}
$.ajax({
url: formURL,
type: "POST",
data: data,
success: function(res) {
if (res == '1') {
$('#show_subscriber_msg').html('<div class=gen>Thanks for your interest in Water Lily Pond. We are going to get in touch with you very soon. </div>');
}
if (res == '5') {
$('#show_subscriber_msg').html('<div class=err>Please enter a valid email address</div>');
}
}
});
e.preventDefault();
//STOP default action
});
</script>
In your success callback, set a timeout for a function that executes your desired behavior.
success: function(res) {
if (res == '1') {
$('#show_subscriber_msg').html('<div class=gen>Thanks for your interest in Water Lily Pond. We are going to get in touch with you very soon. </div>');
setTimeout(yourFunction, 5000);
}
if (res == '5') {
$('#show_subscriber_msg').html('<div class=err>Please enter a valid email address</div>');
}
}
function yourFunction() {
// your code here
}
success: function(res) {
if (res == '1') {
$('#show_subscriber_msg').html('<div class=gen>Thanks for your interest in Water Lily Pond. We are going to get in touch with you very soon. </div>');
setTimeout(function() {
$('#show_subscriber_msg').html('');
}, 5000);
}
if (res == '5') {
$('#show_subscriber_msg').html('<div class=err>Please enter a valid email address</div>');
}
}
Inside the success function I would add a setTimeout, like this:
success: function(res) {
if (res == '1') {
$('#show_subscriber_msg').html('<div class=gen>Thanks for your interest in Water Lily Pond. We are going to get in touch with you very soon. </div>');
setTimeout(function() {
// do what you want, for example:
$('#show_subscriber_msg').html('');
// this number is in milliseconds
}, 500);
}
}
The number, 500 is the number of milliseconds to wait until executing the code
You can use setTimeout to remove the content of $('#show_subscriber_msg') after some seconds
success: function(res) {
if (res == '1') {
$('#show_subscriber_msg').html('<div class=gen>Thanks for your interest in Water Lily Pond. We are going to get in touch with you very soon. </div>');
}
if (res == '5') {
$('#show_subscriber_msg').html('<div class=err>Please enter a valid email address</div>');
}
setTimeout(function(){
$('#show_subscriber_msg').empty()
},5000)
}
empty is a jquery method which is used to remove all child nodes
Try below its worked for me :
success: function(response) {
if (response) {
$('#div_id').hide().html('Write Your message here').fadeIn('slow').delay(6000).hide(1);
}
}
You could also use the jQuery delay if you want to hide it or setTimout
$("#show_subscriber_msg").html('your html').delay(1000).fadeOut();
setTimeout(function() {
// your code to modify or hide the message div
}, 1000)

Only send post/get if form values has changed

I want to prevent multiple ajax calls (user holds enter key down or multi presses submit or other)
I'm thinking, the best way is to use a var with the previous form post values and compare them at each click/submit.. Is it the same? : Then do nothing
But I don't know how to go about it
Here is my javascript/jquery:
$('form').submit(function() {
$theform = $(this);
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
Not very creative with naming vars here:
var serial_token = '';
$('form').submit(function() {
$theform = $(this);
if ($(this).serialize() === serial_token) {
console.log('multiple ajax call detected');
return false;
}
else {
serial_token = $(this).serialize();
}
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
You could combine this with a timeout/interval function which aborts the submit, but the code above should just compare the data in the form
If you have some kind of submit button, just add a class 'disabled' to it when you start the ajax call, and check if it is present before trying to make the call. Remove the class when the server gives a response. Something like:
...
$theform = $(this);
$button = $theform.find('input[type=submit]');
if ($button.hasClass('disabled')) {
return false;
}
$button.addClass('disabled');
$.ajax({
....
},
complete: function () {
$button.removeClass('disabled');
}
});
...

Categories