Refreshing the thankyou message on the form page after submitting - javascript

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)

Related

how do make waiting for ajax to complete

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")
});

I do want to refresh a page after form submission using php and javascript?

I have a form wherein user enters input.Then on submit click a modal popup triggers to confirm data.If user clicks submit in modal ,ajax post is done with alert message but the page doesn't get refreshed automatically and even form data remains as it is?
Even with window.reload() I tried.
Here is the below code
$(document).ready(function(){
$('#submitBtn').click(function() {
validate();
$('#lname').text($('#lastname').val());
$('#fname').text($('#firstname').val());
});
$('#submit').click(function(){
$.ajax({
type: "POST",
url: 'file.php',
data: {
fname: $("#fname").text(),
lname: $("#lname").text()
},
success: function(data){
$("#confirm-submit").modal("hide");
$("#result").html("<div class='alert alert-success'>Inserted Successfully</div>");
}
});
});
setTimeout(function(){ // hide alert message
$("#result").fadeOut();
//alert("hi deepak");
}, 9000);
window.reload();
function validate(){
var valid = $(".classinput").val();
if (valid !== parseInt(valid, 10)) {
//detects floating point numbers like 1.3
alert("Enter integer numbers");
} else if (valid > -1) {
// detects negative numbers
alert("Enter positive numbers");
}
}
});
Try this:
success: function(data){
if(data.success == true){ // if true (1)
$("#confirm-submit").modal("hide");
$("#result").html("<div class='alert alert-success'>Inserted Successfully</div>");
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
}
}
If I understood your problem correctly, then I think you should move your window.reload() into the success AJAX function like so if you want to refresh page after AJAX submit....
success: function(data){
$("#confirm-submit").modal("hide");
$("#result").html("<div class='alert alert-success'>Inserted Successfully</div>");
window.location.reload(true);
}

Ajax Login not returning results

I've created a login box in a modal, but I'm not able to get the results back for some reason. I'm very new to javascript, so I'm guessing it's something obvious!
$('#login').click(function()
{
$("#buttons").hide();
$("#progress").show();
var email=$("#email").val();
var password=$("#password").val();
var dataString = 'email='+email+'&UserPW='+password;
if($.trim(email).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "includes/php/ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function(){
$("#buttons").hide();
$("#progress").show();
;},
success: function(data){
if(data)
{
console.log(data);
if (data = "client/staff")
{
$("#clientStaffToggleButtons").show();
}
if (data = "staff")
{
$("body").load("staff/dashboard.php").hide().fadeIn(1500).delay(6000);
}
if (data = "client")
{
$("body").load("myevent/dashboard.php").hide().fadeIn(1500).delay(6000);
}
if (data = "noEmail")
{
$("#buttons").show();
$("#progress").hide();
//Shake animation effect.
$('#formLogin').shake();
$("#signInSubmit").val('Sign In')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
if (data == "noPW")
{
$("#buttons").show();
$("#progress").hide();
//Shake animation effect.
$('#formLogin').shake();
$("#signInSubmit").val('Sign In')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
}
});
}
return false;
Any ideas on what may be wrong?
Much thanks!! :D
EDIT
Just to clarify, I'm getting the functions back (through console log) but they don't seem to be actually doing anything in the if-then statements, for example:
if (data = "client/staff")
doesn't seem to be doing anything, even if data returned was "client/staff"
to test it out go to fiestausa.com and hit login on the top-right
You're using the assignment operator (=), instead of the comparison operator (=== or == if you don't care about the type), so stuff like this:
if (data = "client/staff")
should become this:
if (data === "client/staff")
The assignment operator returns the assignment value, so in your case the if line from above equals to:
data = "client/staff";
if ("client/staff")
and that evaluates to true since a non-empty strings are truthy.
Incorrect use of comparisons:
$('#login').click(function(e)
{
e.preventDefault();
$("#buttons").hide();
$("#progress").show();
var email=$("#email").val();
var password=$("#password").val();
var dataString = 'email='+email+'&UserPW='+password;
if($.trim(email).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "includes/php/ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function(){
$("#buttons").hide();
$("#progress").show();
;},
success: function(data){
if(data.d)
{
console.log(data.d);
if (data.d == "client/staff")
{
$("#clientStaffToggleButtons").show();
}
if (data.d == "staff")
{
$("body").load("staff/dashboard.php").hide().fadeIn(1500).delay(6000);
}
if (data.d == "client")
{
$("body").load("myevent/dashboard.php").hide().fadeIn(1500).delay(6000);
}
if (data.d == "noEmail")
{
$("#buttons").show();
$("#progress").hide();
//Shake animation effect.
$('#formLogin').shake();
$("#signInSubmit").val('Sign In')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
if (data.d == "noPW")
{
$("#buttons").show();
$("#progress").hide();
//Shake animation effect.
$('#formLogin').shake();
$("#signInSubmit").val('Sign In')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
}
});
}
"return false" is now deprecated.

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');
}
});
...

Limiting search results Javascript

I was wondering how to limit the search result in the Javascript file, my JS file details as following:
/* JS File */
<script>
// Start Ready
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
</script
I just need to add similar to following code to be able to load a loading images before the result and limit the results into five or whatever, and if possible add load more later.
<script>
function loadSearch(query) {
document.body.style.overflow='hidden';
if (typeof xhr != "undefined") {
xhr.abort();
clearTimeout(timeout);
}
if (query.length >= 3) {
timeout = setTimeout(function () {
$('#moreResults').slideDown(300);
$('#search_results').slideDown(500).html('<br /><p align="center"><img src="http://www.tektontools.com/images/loading.gif"></p>');
xhr = $.ajax({
url: 'http://www.tektontools.com/search_results.inc.php?query='+encodeURIComponent(query),
success: function(data) {
$("#search_results").html(data);
}
});
}, 500);
} else {
unloadSearch();
}
}
function unloadSearch() {
document.body.style.overflow='';
$('#search_results').delay(100).slideUp(300);
$('#moreResults').delay(100).slideUp(300);
}
</script>
I have got the 2nd code from another template page, and I am just failing to adjust it to fit my search template (1st code), I'd appreciate it if someone could help me to adjust it, thanks a lot.
If you want to do this on the javascript side, you can use slice.
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html.slice(0, 5);
}
});
I would personally suggest that you do the limiting of rows on the server side to minimize the amount of data you transfer between the client and the server.

Categories