Form not submitting data after validation - javascript

long time reader first time poster. I am having an issue with a form. It has email validator with JavaScript and once the validation is correct it supposedly has to submit the data but this doesn't happen. If I run the form without the validation the data goes through without a problem but with the validation I have a success message and then no data.
function ValidateEmail(email)
{
var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if(!email.match(mailformat))
{
alert("valid email is required");
return false;
}else{
document.querySelector('form').submit();
setTimeout(function(){
window.parent.location = "https://www.xxxs.com/";
}, 3000);
}
}
window.onload= function(){
document.querySelector('input[type="submit"]').addEventListener("click",
function(e){
e.preventDefault();
var email = document.querySelector('input[name^="Email"]').value;
ValidateEmail(email);
});
}
Thank you for your help

You haven't provided the markup to go along with it, so I can only speculate that there's a problem with the markup.
I also have no idea why you've added this.
setTimeout(function(){
window.parent.location = "https://www.xxxs.com/";
}, 3000);
Apart from this, it works pretty well for my sandbox.
PS: I can't comment yet due to reputation, but #Kayden van Rijn might be interested in
/* Links that start with "https" and end in ".org" */
a[href^="https"][href$=".org"] {
color: green;
}
from MDN Web Docs

Related

why JavaScript form works in Chrome but not in Firefox

i need following function to be execute in Firefox.., but it is working fine in chrome. the problem was when i do 'Inspect Element With Firebug' it is working fine. the method 'EditEncounterBillStatus' is also hitting correctly. but when i don't use 'Inspect Element With Firebug' the method EditEncounterBillStatus is not hitting.. i tried a lot to sort out this. but still i can't can any one help me to find solution thanks in advance.
else if (element.trim() == "Approved") {
var TestPin = prompt("Please Enter your PIN");
if (TestPin != null) {
if (isNaN(TestPin)) {
alert("Please Enter a Valid Pin");
return;
}
else if (TestPin == pin) {
var postVisitData = { VisitId: vid};
$.post("/Emr/WaitingRoom/EditEncounterBillStatus", { VisitId: vid }, function (data) {
});
window.location = "/Emr/Patients/Show?PID=" + pid;
}
else {
alert("Your Entered PIN Is Incorrect");
}
}
else {
return;
}
}
I would recommend doing it like this
else if (TestPin == pin) {
$.post("/Emr/WaitingRoom/EditEncounterBillStatus", { VisitId: vid }, function (data) {
window.location = "/Emr/Patients/Show?PID=" + pid;
});
return; // in case of side effects in unseen code
}
i.e. wait until the $.post has finished before changing the window.location
As the rest of your code is unseen there could be side effects of performing this in this way - hence the return where it is - but even then, not knowing the full call stack there could still be side effects - you have been warned
You should change location upon the success of the post call, so put that in your callback function body:
$.post("/Emr/WaitingRoom/EditEncounterBillStatus", { VisitId: vid },
function (data) {
window.location = "/Emr/Patients/Show?PID=" + pid;
});
This way you are sure you only change location when the post action was executed. Otherwise you risk that you change location before the post happens. In debug mode, and certainly when you step through the code, there is enough time for the post to finish in time, and so your original code then works.

Javascript onUnload Show offer and redirect to offer page if stays on page [duplicate]

Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.

Seeking more elegant solution to preventDefault() dilemma

I have a jQuery form-submission routine that has an input integrity check in ERROR_CHECK.PHP that relies on GET variables passed to it for inspection. If the values passed to it are malformed, then an alert box appears that explains the error and how the form data should be remedied. This alert box will need to pop up until the form data is no longer malformed, at which point that data is used for repopulating data on the page.
Thus, in the jQuery routine I'm at the mercy of our friend preventDefault(), and I have found a solution that does work, but not elegantly. The variable allowSubmit is initialized as FALSE and remains that way—with preventDefault() also in effect—until the form data passes the integrity check, at which point allowSubmit switches to TRUE...but that only happens with the submission of the correctly-formed input data. This means the user must submit the form a SECOND TIME in order for the form data to be used to replace data on the page...and that, of course, is not a solution (press the submit button twice?)
However, by dynamically submitting the form (here, with the $('#my_form').submit() statement) immediately after resetting allowSubmit to TRUE, I've submitted the form again, thereby allowing the user to submit correctly-formatted data ONCE, as it should be from the get-go.
This is obviously a band-aid solution and not elegant. Can anyone see a more elegant way to structure this? (I'm working with jQuery fashioned by another developer, and this occurs in the midst of a longer self-calling JQuery function, and I have to work with it on its own terms, lest I have to refashion all other parts of the larger function in which it occurs.
Here's a distillation of the code (with self-describing variables, etc.), which works as described, although not as elegantly as I'd like:
var allowSubmit = false;
$('#my_form').on('submit', function(e) {
if (!allowSubmit) {
e.preventDefault();
// Check to see if input data is malformed:
$.get('error_check.php', { new_element_name: $('#new_element_name').val() }, function(data) {
if (data != 0) {
alert("An Error Message that explains what's wrong with the form data");
} else {
allowSubmit = true;
// The line below--an auto-submit--is needed so we don't have to press the submit button TWICE.
// The variable allowSubmit is set to TRUE whenever the submitted form data is good,
// but the code suppressed by e.preventDefault() won't execute until the form is
// submitted a second time...hence the need for this programmatic form submission here.
// This allows the user to correct the errant form data, press the submit button ONCE and continue.
$('#my_form').submit();
}
});
}
$('#element_name').val($('#new_element_name').val());
});
What you are doing is okay, your other options might be to write a click handler for a generic button and submit the form through that event after validation, then you wont need to preventDefault as you won't be preventing any kind of submit action. Another solution might be to re-trigger the event after validation.
$("button").click(function() {
$("#my_form").submit();
});
...
allowSubmit = true;
// alternatively
jQuery( "body" ).trigger( e );
...
The callback solution you have doesn't seem unreasonable. I agree with #scott-g that a generic button click event handler would probably be your best bet. A more testable way to write what you have here may be:
var formView = {
$el: $('#my_form'),
$field: $('#element_name'),
$newField: $('#new_element_name'),
$submitBtn: $('#btn-submit')
}
var handleSubmit = function() {
var formData = formView.$field.val();
remoteVerify(formData)
.done(formView.$el.submit)
.done(updateForm)
.fail(handleVerificationError);
};
var remoteVerify = function(formData) {
var deferred = $.Deferred();
var url = 'error_check.php';
var data = { new_element_name: formData };
$.get(url, data)
.done(handleRequest(deferred))
.fail(handleRequestErr);
return deferred;
};
var handleRequest = function(deferred) {
return function (data, jqxhr) {
if (data != 0) {
deferred.reject(jqxhr, "An Error Message that explains what's wrong with the form data");
} else {
deferred.resolve(data);
}
}
};
var handleRequestErr = function() {
// error handling
}
var updateForm = function () {
formView.$field.val(formView.$newField.val());
}
var handleVerificationError = function (jqxhr, errMsg){
alert(errMsg);
}
formView.$submitBtn.on('click', handleSubmit)
You could try using an async: false setting using $.ajax (I don't know what your php is returning, so I am just "pretending" it's a json array/string like so echo json_encode(array("response"=>$trueorfalse));):
<script>
$('#my_form').on('submit', function(e) {
var valid_is = true;
// Check to see if input data is malformed:
$.ajax({
async: false,
url: 'error_check.php',
type: 'get',
data: { new_element_name: $('#new_element_name').val() },
success: function(response) {
var Valid = JSON.parse(response);
if(Valid.response != true) {
alert("An Error Message that explains what's wrong with the form data");
valid_is = false;
}
}
});
if(!valid_is)
e.preventDefault();
$('#element_name').val($('#new_element_name').val());
});
</script>
If you use async: false it runs the script in order and waits to execute the rest of the script until after it receives a response. Scott G. says you can do it with what you have with some slight modifications so I would try that first.

Java Script Only one function call works

I have a simple registration form. As soon as the user types his phone number and leaves the textbox (onblur), a few of the other fields get auto populated, using an Ajax call to a php script, and this piece works fine. Now, I'm trying to add another onblur() event ON A DIFFERENT TEXT FIELD that has nothing to do with the ajax call or the fields populated but is in the same form. However, when I create this function in java script, the event does not get fired. More over, the original ajax call also stops working i.e., the onblur event for the phone number field also does not get fired (I've confirmed this by putting a few alert messages in place). I'm stuck and given that I'm a novice web developer, it has been an irritable ride. So any help or a nudge in the right direction would be appreciated.
My java script code is in the same file as my HTML code, i.e., between the tags. When I create both the functions between the same script tags, none work, but when I put them in separate script tags, the first function (ajax call behind Phone number) gets fired on blur but the second one does not. The functions in point are: vldtnPhNo() and enabtnRegCmplt().
<script type="text/javascript">
function vldtnPhNo()
{
var xhr;
var dvPhNo = document.getElementById("divPhNo");
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
var FoneNumb = document.getElementById("txtPhNo").value;
xhr.open("POST", "verify.php", true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
document.getElementById("txtRegInv").value = xhr.responseText;
var rstOftheTxt = xhr.responseText;
document.getElementById("txtPhNo").value=rstOftheTxt;
document.getElementById("txtPhPop").value=rstOftheTxt;
}
else
{
document.getElementById("txtPhNo").value='waiting';
document.getElementById("txtPhPop").value='waiting';
}
}
}
xhr.send("txtPhNo=" + FoneNumb);
}
else
{
throw new Error("Ajax is not supported by this browser");
}
}
function enabtnRegCmplt(){
If(txtRegInv.value!="")
{
var UsrNm;
var Psswd;
var RePsw;
var PostBackInfo;
UsrNm = document.getElementById('txtUsrNm');
Psswd = document.getElementById('txtPsw');
RePsw = document.getElementById('txtrePsw');
txtRegInv = document.getElementById('txtRegInv');
If (RePsw.value!="" && Psswd.value!="" && UsrNm.value!="" && RePsw.value==Psswd.value)
{
document.getElementById('btnRegCmplt').disabled="False";
}
else if(UsrNm.value=="")
{
UsrNm.value="Please Enter UserName";
}
else if(Psswd.value=="")
{
Psswd.value="Please Enter Password";
}
else if(RePsw.value=="")
{
RePsw.value="Does not match";
}
}
}
</script>
Your code is very messy. One of the reason why it's necessary to write neat code. Your brackets are wrong, thus the whole code isn't executed (else statement is connected with function).
The If statement doesn't exist, try if instead (lowercase I).
Other things:
use onkeyup instead.
2:
For the vars you could do:
var UsrNm,
Psswd,
RePsw,
PostBackInfo
;
OR
var UsrNm = document.getElementById('txtUsrNm'),
etc.
Syntax mistake
An extra brace }
`else
{
document.getElementById("txtPhNo").value='waiting';
document.getElementById("txtPhPop").value='waiting';
}
}
}`
Remove one brace after the else condition

What JavaScript function will auto-submit a Qualtrics survey?

What JavaScript function will auto-submit a Qualtrics survey? I want to create a button in the header or footer of a Qualtrics survey that will automatically submit the survey whenever the user wants to quit. It seems like a pretty standard feature for survey software to have. The question may not seem well researched but that's because there are NO Qualtrics resources out there on this.
I found parts of the Qualtrics JS that might be relevant:
function pressSubmitButtonOnEnter(evt, id) {
if (evt.keyCode == Event.KEY_RETURN) {
Event.stop(evt);
$(id).click();
return false;
}
}
This one as well:
function submitForm(formID) {
var form = $(formID);
if (form) {
Event.fire(form, 'submit');
if (form.onsubmit)
form.onsubmit();
if (form.submit)
form.submit();
return true;
}
}
function submitFormJumpTo(formID, jumpTo) {
$(formID).action = jumpTo;
submitForm(formID);
}
This:
var SEonSubmit = {
add : function (onSubmitFunction) {
Event.observe('Page', 'submit', onSubmitFunction);
}
};
var SEonClick = {
add : function (onClickFunction) {
Event.observe('Page', 'click', onClickFunction);
}
};
According to Qualtrics, there is no way to do this. I submitted a request feature.
This question is still relevant almost seven years later. I just spent a crazy amount of time trying to get this to work, it is exceptionally poorly documented.
The page with the intercept will have the QSI.API object.
QSI.API.load()
QSI.API.run()
Site Intercept JavaScript API
https://s.qualtrics.com/WRAPI/SiteIntercept/JavaScript/classes/API.html

Categories