JS/Ajax: grab input field value without refresh or button click - javascript

I am currently using js function to submit data without page refresh or button click. The input field is inside tab #2 that executes the js once the user stops typing. The problem is that the js is making the page refresh thus taking me back to tab#1. How can I prevent the page from refreshing? I thought i had included the necessary code in the JS function to stop this. EXAMPLE
<script>
$(document).ready(function() {
var timer;
$('#video-input1').on('keyup', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
//do your submit here
$("#ytVideo").submit()
//alert('submitted:' + value);
}, 2000);
});
//submit definition once submit is executed
$('#ytVideo').submit(function(e){
e.preventDefault(); //prevent page refresh
var form = $('#ytVideo').serialize();
//submit.php is the page where you submit your form
$.post('index.php#tab-2', form, function(data){
var x = $(data);
$("body").html(x);
});
return false;
});
return false;
});
</script>

try changing this line
//do your submit here
$("#ytVideo").submit()
to
$("#ytVideo").trigger("submit");
i believe the problem is that you define what submit should do after the form has been submitted this causes the page to reload.
Edited
try this change
$('#ytVideo').submit(function(event){
event.preventDefault(); //prevent page refresh
event.stopPropagation(); //+
var form = $('#ytVideo').serialize();
//submit.php is the page where you submit your form
$.post('index.php#tab-2', form, function(data){
var x = $(data);
$("body").html(x);
});
//- return false;
});
//- return false;
made some changes

Instead of .submit() you should use .triggerHandler('submit'). Docs and related question.

Related

MVC - Issue with users double-clicking Submit button

I have a number of pages in my MVC app where the user clicks a Submit button to post a form. Sometimes users will click Submit and since nothing happens immediately, click it again. Therefore, the form submits twice. To prevent this, I have the following JavaScript code:
// When the user submits the form, disable the Save button so there is no chance
// the form can get double posted.
$('#form').submit(function () {
$(this).find('input[type=submit]').prop('disabled', true);
return true;
});
This code disables the Submit button so the user cannot click twice. This works fine. However, if there are client side validation errors on the form, the Submit button gets disabled but the form is never posted, and now the user cannot post the form. Is there a change I can make to the JS code to detect if there were client side validation errors, and, if so, I either don't disable the Submit button, or reenable it?
If you are using jQuery Validate, you can check to see if the form is valid before disabling the button:
$('#form').submit(function () {
if ($(this).valid()) {
$(this).find('input[type=submit]').prop('disabled', true);
}
});
You can try something like this:
<button id="subButton" /> <!-- do not use type="submit" because some browsers will automatically send the form -->
Javascript:
$('#subButton').click(function (e) {
e.preventDefault(); //prevent browser's default behaviour to submit the form
$(this).prop('disabled', true);
doValidation();
});
var pTimeout;
function doValidation() {
ajaxLoader.show(); //lock the screen with ajaxLoader
var form = $('#registerForm');
var isPending = form.validate().pendingRequest !== 0; // find out if there are any pending remote requests ([Remote] attribute on model)
if (isPending) {
if (typeof pTimeout !== "undefined") {
clearTimeout(pTimeout);
}
pTimeout = setTimeout(doValidation, 200); //do the validation again until there are no pending validation requests
}
var isValid = form.valid(); //have to validate the form itself (because form.Valid() won't work on [Remote] attributes, thats why we need the code above
if (!isPending) {
ajaxLoader.hide();
if (isValid) {
$('#registerForm').submit(); //if there are no pending changes and the form is valid, you can send it
}
else {
$('#subButton').prop('disabled', false); //else we reenable the submit button
}
}};
Switch it around.
$("input[type='submit']").on("click", function (event) {
event.preventDefault();
$(this).prop("disabled", true);
// perform error checking
if (noErrors) {
$("#form").submit();
}
else {
$(this).prop("disabled", false);
}
});

Stop auto triggering a click after page reload

I have code that fill in an input field and then triggers a click on a submit button within a form if a certain text exists in a specific div, so that makes a pages refresh on submit.
I also have a link inside the same form that if clicked it removes the input value that was filled before and also submit the form. Since it submit the form, it triggers a page refresh which leads to executing the first event that fill in the input field and trigger a click on the submit button again.
I want to stop auto triggering that click if the link was clicked by the user.
Perhaps the code explain better...
JS :
$(document).ready(function () {
$("#link").click(function () {
sessionStorage.reloadAfterPageLoad = true;
window.location.reload();
});
$(function () {
if (sessionStorage.reloadAfterPageLoad) {
//Some code that I don't know to prevent executing the below code after page refresh if #link was clicked by user.
alert("Link Clicked");
sessionStorage.reloadAfterPageLoad = false;
}
});
if (document.getElementById('divid').innerHTML.indexOf("Sampletext") != -1) {
document.getElementById('inputid').value = 'example';
$("#button").trigger('click');
}
});
HTML :
<div id="divid">Sampletext</div>
<input type="text" id="inputid" />
<input type="submit" id="button" value="Enter" />
Do This
Answers are greatly appreciated.
It seems you're setting the reloadAfterPageLoad flag, but then you aren't doing anything meaningful with it.
Try replacing the bottom part of your code with something like this;
if (document.getElementById('divid').innerHTML.indexOf("Sampletext") != -1 && sessionStorage.reloadAfterPageReload == true) {
document.getElementById('inputid').value = 'example';
$("#button").trigger('click');
}
});
If you set an item in local storage that you use to determine if the click has been triggered, you could use that to determine if it should trigger after reload. local storage persist between page request.
$(document).ready(function () {
var triggered = parseInt(localStorage.getItem('triggered'));
$("#link").click(function () {
sessionStorage.reloadAfterPageLoad = true;
window.location.reload();
});
$(function () {
if (sessionStorage.reloadAfterPageLoad) {
//Some code that I don't know to prevent executing the below code after page refresh if #link was clicked by user.
alert("Link Clicked");
sessionStorage.reloadAfterPageLoad = false;
}
});
if (document.getElementById('divid').innerHTML.indexOf("Sampletext") != -1) {
document.getElementById('inputid').value = 'example';
if (!triggered) {
localStorage.setItem('triggered', 1);
$("#button").trigger('click');
}
}
});

Run AJAX function on form submit button after javascript confirm() cancel

I have a form where and AJAX function runs on form submission to make sure that the data in the form doesn't conflict with data in the database. If a conflict is found, the AJAX function pops up a confirm() box. If the user clicks "OK", the form is submitted. If they click "Cancel", the form is not submitted.
Here's where things get problematic. If they click cancel and then adjust the values in the form and submit it again, the AJAX function does not run the next time they hit the form submit button. Is there a way to make the AJAX function run every time they hit submit, even if they have previously cancelled the form submission?
Here is a truncated version of the AJAX function:
$('#publish').one('click', function (e) {
e.preventDefault();
var url = shiftajax.ajaxurl;
var shift = $('#post_ID').val();
var data = {
'action': 'wpaesm_check_for_schedule_conflicts_before_publish',
'shift': shift,
};
$.post(url, data, function (response) {
if( response.action == 'go' ) {
// submit the form
$('#post').submit();
} else {
// ask user for confirmation
if (confirm(response.message)) {
// user clicked OK - submit the form
$('#post').submit();
} else {
// user clicked cancel - do nothing
}
}
});
});
Like I said, this is working just fine, but the AJAX doesn't fire at all if you hit the submit button after hitting the "cancel" button.
For what it is worth, this AJAX function runs when you hit the "Publish" button on a WordPress custom post type.
Dont use one(it will fire ajax submit or button click only once) , use here var IsBusy to check user is not repeatedly pressing the form submit,
Try below code,
var isBusy = false; //first time, busy state is false
$('#publish').on('click', function (e) {
if(isBusy == true)
return ; //if Busy just return dont submit
else
isBusy= true; //true , tell that ajax is now busy processing a request
e.preventDefault();
var url = shiftajax.ajaxurl;
var shift = $('#post_ID').val();
var data = {
'action': 'wpaesm_check_for_schedule_conflicts_before_publish',
'shift': shift,
};
$.post(url, data, function (response) {
if( response.action == 'go' ) {
// submit the form
$('#post').submit();
} else {
// ask user for confirmation
if (confirm(response.message)) {
// user clicked OK - submit the form
$('#post').submit();
} else {
// user clicked cancel - do nothing
}
}
isBusy = false;
});
});

Check existing mail with ajax and PHP

Is there any method to check if the mail (in a registration form) exist in my database while i'm writing it (before i click submit buttom).
This is my javascript function it work well when I click submit button:
<script type="text/javascript">
$(document).ready(function(){ //newly added
$('#_submit').click(function() {alert('in');
var emailVal = $('#mail').val(); // assuming this is a input text field
$.post('checkemail.php', {'mail' : emailVal}, function(data) {
if(data=='exist') return false;
else $('#form1').submit();
});
});
});
</script>
but I want to verify the mail before I submit (without I click any button)
I believe #_submit is a submit button. In that case, your <from> will be submitted without waiting for the ajax call to complete, since that is an asynchronous task.
In order to work around this, you should prevent the <form> submission by default, and once the ajax call completes, decide whether to submit the form or not depending on the response.
$(document).ready(function() { //newly added
$('#_submit').click(function(e) {
e.preventDefault(); // prevent default submission
alert('in, submission prevented - waiting for ajax response');
var emailVal = $('#mail').val(); // assuming this is a input text field
$.post('checkemail.php', {
'mail': emailVal
}, function(data) {
if (data == 'exist')
return false;
else
$('#form1').submit();
});
});
});
or you can simply use a type="button" button so that it doesn't trigger <form> submission.
something like that
$.ajax(url).done(function(response) {
if (response === true) {
$(form).submit();
} else {
console.log("not allowed");
});

Leave a page during a registration

I want to make a confirmation before user leaving the page if there's a incomplete registration or refresh the registration page
JQUERY CODE:
$(document).ready(function(){
$('input[name=subdomain]').keyup(subdomain_check);
$('input[name=password]').keyup(password_strenght);
$('input[name=c_password]').keyup(password_check);
$('input[name=email]').keyup(email_check);
$("#install").on('submit', function(){
return subdomain_check() && password_strenght() && password_check() && email_check();
});
window.onbeforeunload = function() {
return 'Are you sure you want to navigate away from this page?';
};
});
But the confirmation pop up in every step of the registration, even if the registration is complete! How can I prevent that from happening?
You need to put this code in js file,
/* Dirty Flag */
$(document).ready(function() {
is_dirty = false;
$(window).bind('beforeunload', handle_unload_event);
setDirtyFlag("form1");// Here form1 is the ID of form
});
function setDirtyFlag(frmID){
$('#'+frmID).find(':input').each(function(){
$(this).change(function(){
is_dirty = true;
});
});
}

Categories