Javascript return issue - javascript

This problem has just become apparent in some historical code and seems to be an issue relating to IE8 + and FF4 +
I have a js file that validates a contact form, one particular section calls a function to open a new window with some info for the user. At this point the script seems to ignore my valid = false variable (which is flagged to stop form submission)
function showFormat() {
var myWindow;
myWindow = window.open("http://url/page.html","Postcode_Information","location=1,status=1,scrollbars=1,width=640,height=400");
myWindow.moveTo(50,50);
}
Above code is causing the issue. i've tried adding valid=false; return valid; to the end of the function but it is apparently being ignored. Adding this to the begining of the function means that the validity is correct and the form doesnt submit but obviously my new window doesnt open.
EDIT TO EXPLAIN IN MORE DETAIL
My js file has a series of validation functions (checking username, address, email address validity etc). A variable is initialised called valid which will always be true unless any user input does not validate, in which case valid = false.
If valid = false then an if statement is run which checks against a number of variables in order to determine which area of the validation has caused the problem and will flag up an appropriate prompt. Most of these are done via a message box (I inherited this code and am merely trying to get it working) but one prompt opens up a new window. If any of these prompts are called at all then the form should not be submitted.
The problem I am having is that when this new window opens (and this is the only prompt causing this issue) the form will still submit.
See code below for an example of when these prompts are called:
if (!valid) {
if (emailNoAddress == true) {
alert('You have requested to receive more information by email from other company(ies) but have not provided email address details – Please correct this below');
highlightEmail();
}
else {
if (contactDetails == false) {
alert('Please provide your email address details. We will not send you future correspondence and offers by email if you prefer us not to.');
highlightAddress();
highlightEmail();
}
else {
if (postcodeGiven == false) {
if (dataform.pcode.value == "") {
alert('Please enter a valid postcode');
}
else {
showFormat();
}
}
else {
if (questionsAnswered == false || countryGiven == false) {
alert('Please choose an answer from the options provided');
}
else {
//alert(checkstr);
alert('Could you please complete the questions missing details');
}
}
}
}
}
So you see, my function can only be called when !valid in which case the form should not submit but as soon as I execute the new window function showformat() it allows the form to be submitted.
EDIT - UPDATE
I've managed to narrow the problem down slightly in that after the new window opens, no more script is executed (i've tried adding a few alert messages to check the value of valid but they are not shown - I've also tried adding a breakpoint while debugging with Firebug but this is not hit) and the form submits regardless...
EDIT - UPDATE
Beacuse this was a time-critical issue, for the moment I have just put all the text from the pop-up window into an alert and call that instead of the function. When I have any more time to spend investigatin I will update.

Are you having the onsubmit event defined on the form tag? If so then add the keyword return in the onsubmit event like shown below
onsubmit = "return some_function" and in the function called u have to specify return false. Then u will be getting wat u want.
Hope this helps you.

Here is the SImple example which works as u need. Try this and correct ur code accordingly
<html>
<head>
<script type="text/javascript">
function validate()
{
if(document.forms[0].stext.value!="")
{
return showformat();
}
else
return false;
}
function showformat()
{
window.open("new.html","");
return false;
}
</script>
</head>
<body >
<form name="sample" action="onsel.html" method="post" onsubmit="return validate()">
<input type="text" name="stext" id="stext" value="" />
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Hope this helps you

Related

How to protect HTML form from blank submission

Basically I'm using this tutorial: HTML FORM
Everything is working as it should but one flow I've found is that everyone can see the URL for your .php which in this case is "url: "contact_mail.php""
Is there a way to protect my form from blank submission when someone type the url and just press enter.
Example: www.mywebsite.com/contact_mail.php
Thank you!
First you can use the required attribute on mandatory fields for client-side:
<input type="text" name="mandatory_field" required>
But you will need to verify server-side in case the user modified the form. You can use empty() on any variable ($_POST or $_GET):
if (empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
You can use isset() to verify if a field is submitted. Your validation could be:
if (!isset($_POST['mandatory_field']) || empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
Other cases:
If all fields are mandatory you could check with in_array():
if (in_array(false, $_POST)) {
// print error message or redirect to form page
}
If doing various data validation here is what I use to do with forms:
$errors = [
'empty field' => empty($_POST['field']),
'another error message' => $another_condition
];
if (in_array(true, $errors)) {
$error_message = array_search(true, $errors);
// print or redirect, and you can tell the user what is wrong
}
Say you have the following form;
<form action="savething.php" method="GET" name="mythingform">
<input name="thing1" type="text" />
<input name="thing2" type="text" />
<input type="button" value="Submit" onclick="validateAndSubmit()" />
</form>
In this, instead of a submit type input, I have used a button. This means, something needs to happen before the page will submit, so, for example;
<script>
function validateAndSubmit()
{
var thing1 = document.getElementsByName("thing1")[0];
var thing2 = document.getElementsByName("thing2")[0];
if (thing1.value.length > 0 && thing2.value.length > 0)
{
document.forms["mythingform"].submit();
}
}
</script>
The JavaScript function here will only call the submit on the form when the inputs are not empty
In terms of stopping someone from accessing this without permission;
<?php
if (!isset($_REQUEST['myvariable'] || empty($_REQUEST['myvariable']))
die("Please make sure the form has been submitted properly with all required information");
Using die in this, will terminate execution of the script any further, you can also use exit and both allow you have have a "termination message" attached to them as part of the stoppage process
$_REQUEST isn't the safest of options, but it permits you to use GET or POST methods from forms to be able to retrieve and use data
Form blank submission you can use java-script validation or jquery validation validation or you can also use php validation to avoid blank form submission.
core js validation
simple example:
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
jquery validation
validation library
https://jqueryvalidation.org/documentation/
example:
$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
I hope it helps.
(1) there should be no danger from someone 'just entering' the URL in their browser - the back-end code is supposed to respond only to POST, not to GET (entering a URL in a browser makes it issue a GET request for the given URL).
(2) the quoted example code already includes client-side validation (including checks for empty fields), so if someone legitimately uses your entry form, they will not be able to send a blank form.
(3) all that remains is to protect the back-end code from accidental or malicious posting of empty forms (and any other use that is undesirable). The example PHP code doesn't have any checks, you should add some - like the isset(...) or empty() checks suggested in another answer here).
Use if (empty($_POST['your_field']))
So if a post or get query reaches your php script, empty will check if the field is empty or not.
So something like this:
if (empty($_POST['your_field'])) {
echo 'Field xxx should not be empty';
}
Although isset would be better, since if they just go to the link, your POST and GET variables are empty.
So something like this is kinda foolproof:
if (!isset($_POST['your_field']) || empty($_POST['your_field'])) {
echo 'Field xxx should not be empty';
}
Didn't think i'd need a separate piece of code for GET, but ok.
if (!isset($_GET['your_field']) || empty($_GET['your_field'])) {
echo 'Field xxx should not be empty';
}

Return Javascript function within document.write('<a href="">')

I have this javascript:
document.write('<a HREF="javascript:return validateForm();' + thisform + '.submit();void(0);"');
I also have the following function, referencing a form on my website.
function validateForm()
{
var y=document.forms["myForm"]["email"].value;
if (y==null || y=="") {
alert('Please enter your email to continue.');
return false;
}
}
Now how do I get that return in the HREF to work!? It won't return false in the case that the input equals "" and validateform() returns false.
Your code:
document.write('<a HREF="javascript:return validateForm();' +
thisform + '.submit();void(0);"');
Seems incomplete. If you are using a link, then the href should link to a useful resource. If not, use a button or some other UI object that clearly indicates what will occur.
Returning false using the javascript pseudo protocol for the href attribute does nothing. The void statement does nothing at all (that is the point of void). Also, void is an operator so no need to include the grouping operator ().
You can't use an A element like this to conditionally submit the form, you really should be using the form's submit event to conditionally allow or prevent the submit. You can do:
document.write(
'<a href="http://useful.com" onclick="return validateForm(' +
thisform + ');">do stuff<\/a>');
Then within the validateForm function you can conditionally call the submit method of the form.
If validateForm returns false, the browser will not follow the link.
A far better strategy is to put the listener on the form:
<form onsubmit="return validateForm(...)" ...>
If validation fails, return false and the submit will be cancelled. Otherwise, the submit will continue.
In order to control the form submission appropriately, you should have this kind of solution:
document.write('<a href="#" onclick="submitMyForm(' + thisForm + ');"');
Then have this JS function:
function submitMyForm(theForm) {
var y = theForm["email"].value;
if (y==null || y=="") {
alert('Please enter your email to continue.');
} else {
theForm.submit(); // will only submit the form if it's valid
}
}
Why do you have
alert("Not a valid e-mail address.");
document.location = "http://www.snarephoto.com/about/";
stopnow()
return false;
I think you should only have..
alert("Not a valid e-mail address.");
return false;
Also, what does stopnow do in your case?
I don't know why you don't have to return a function inside a href, but this is really non recommended.
I'm not really answering your question. But I can not figure out what the situation would be truly necessary to use it out instead of Javascript OOP.
I strong recommend to adapt your code to a non obstrusive way like that.
Body:
<p>Item 1</p>
Script
<script type="text/javascript">
var myFunction=function(){
//do something
alert('You clicked me!');
alert('This function is inside '+this.innerHTML+' Link');
this.style.backgroundColor='Yellow';
}
document.getElementById('myLink').onclick=myFunction;
</script>
This not call the function directly, a reference in memory is created (like pointers in C) in the Virtual Machine. and the most important NONE EVAL is used, and are much faster then inline eval.

Why does .match() stop my code from executing?

I'm having trouble with a form I'm trying to validate. I'm trying to make sure for the email input that the email is the correct format, and if it is not I'll be able to send an error message to the user. Unfortunately, I can't get the return false; to execute.
Here is my current code:
function validate(){
var email = $('input.email').value;
var emailRE = /^.*#.+\..{2,5}$/;
if (email.match(emailRE)){
alert("This is true");
} else {
alert("This isn't true.");
}
return false;
}
When I execute this, the page reloads and the form submits, and neither alert goes off. However, when I take out the whole if, else section, the return false; executes, and the page doesn't reload. I also tried taking out just the '.match()', and the code executed fine. So what is wrong with the .match() part that's causing it to fail?
Any help is extremely appreciated. Thank you!
You have to use $('input.email').val() instead of $('input.email').value
http://jsfiddle.net/bMJH2/6/
value is for the DOM object. But the object you are dealing with is a jQuery object, so the proper way is to use val(). If you run it in Firefox/Firebug using value, it will show the error:
email is undefined
[Break On This Error] if (email.match(emailRE)){

Jquery validation before form submits to php

I have tried and tried with this and don't seem to be getting anywhere, so thought I would put it out there. I have a form full of data provided by the user that I have thus far been able to validate with js/jQuery without problem before sending it to php for further processing. I am achieving this like so:
form.submit(function(){
if(validateUserName() & validateEmail1() & validateEmail2() & validatePass1() & validatePass2() & acceptTerms()){
return true;
} else {
return false;
}
});
The form itself uses the following attributes:
<form id="signup" action="registration.php" method="post">
The problem function is acceptTerms(), which simply has to check that a checkbox is selected does not seem to work as it should (or as the rest of the validation functions do).
var termscons = $('input:checkbox[name=termscons]');
termscons.change(acceptTerms);
function acceptTerms(){
if($(termscons).is(':checked')) {
termsconsInfo.text("");
return true;
} else {
termsconsInfo.text("In order to join, you must accept these terms and conditions.");
return false;
}
}
I have integrated the termscons.change listener and termsconsInfo.text(""); to ensure that my selectors are pointing at the right thing, and that the function is being fired correctly (which it appears to, by changing the termsconsInfo.text when its state changes). When I try to submit the form however it appears to return false, since it does not submit. It should in fact be returning true, and posting my form over to my php script.
Am I going about this the right way? Is there something I have been missing when dealing with a checkbox as opposed to a textinput?
Please excuse my ignorance, this is all still very new to me.
First problem is that you are using & in your if statement. It needs to be &&.
Second problem is with acceptTerms (as you guessed):
var termscons = $('input:checkbox[name=termscons]');
termscons.change(acceptTerms);
function acceptTerms(){
if(termscons.is(':checked')) { // <-- termscons is already a jQuery object
termsconsInfo.text("");
return true;
} else {
termsconsInfo.text("In order to join, you must accept these terms and conditions.");
return false;
}
}
There might be more, but that is what I see for now.
i say forget reinventing the wheel and use something already tested for instance jQuery validate

Calling JS Function on Form Submit

I have created a JS function which executes fine when it's included an the 'onclick' action of standard HTML link tag as follows:
test
However where I really want to use this function is on the 'onsubmit' action of a form but when I include it as follows the function no longer seems to be executing:
<form action="page.pl" id="disable-submit" name="status-form" method="POST" onsubmit="return fb_CheckPermission('publish_stream');">
What the 'fb_CheckPermission()' JS function basically does is use Facebook Connect to check to make sure the user has granted us a specific permission and if not it tells Facebook Connect to prompt the user to grant the permission. Here is the code for the JS function:
1. function fb_checkPermission(permission) {
2. FB.ensureInit(function() {
3. FB.Facebook.apiClient.users_hasAppPermission(permission, function (hasPermissions) {
4. if(!hasPermissions){
5. FB.Connect.showPermissionDialog(permission,function (status){
6. if(!status) {
7. if(permission == 'offline_access') {
8. // save session
9. }
10. }
11. });
12. }
13. });
14. });
15.}
What this code does is as follows:
Line 2: Make sure Facebook Connect JS library is loaded
Line 3: Checks to see if the current Facebook Connect user has granted a specific permission
Line 5: If the permission hasn't been granted then prompt the user with the permission dialog
Line 7: In the case of the 'offline_access' permission save the session key once granted
The user experience I'm trying to achieve is that when a user submits the form I'll check to see if they have granted a specific permission and if not prompt them for the permission before submitting the form. If the user has already granted the permission the form should just submit. For those users who are prompted the form should submit after they either choose to grant the permission or if the deny the request which I believe the fb_checkPermission() JS function is handling correctly right now. What I'm not sure is if there is some kind of JavaScript issue with how this works on form submission.
As I mentioned, this JS function works perfectly as an onclick action but fails as an onsubmit action so I'm pretty sure that this has something to do with how JavaScript treats onsubmit actions.
I'm stuck so I really appreciate your help in figuring out how to change the JS function to produce my desired user experience. Thanks in advance for your help!
The reason your "click on anchor" works is because it does not change your page (location) while all of the Facebook asynchronous calls finish.
When you attach the same function to the submit handler the function returns before Facebook stuff gets actually executed, and it does without returning "false" causing the form to proceed with submission earlier than you want it to.
What you need to do is return "false" at the end of your onSubmit function to prevent submission and give time to Facebook stuff to finish and then manually submit form at places you want it to be submitted by calling:
document.getElementById('disable-submit').submit();
(The handler will not be called if submittion is triggered from the script.)
Unfortunately I don't have Facebook SDK at hand so I can't write the code that I'm sure works 100%, but it's something along these lines:
function onSubmit () {
doStuffAsynchronously(function () {
if (everythingIsOK) {
// proceed with submission
document.getElementById('formId').submit();
}
});
return false;
}
Try putting the javascript call on the input you are using to initiate the submit.
I think basically that your browser tends to use default validation form (page.pl / method POST) instead of doing what you think it does
Try this
<form action="page.pl" id="disable-submit" name="status-form"
method="POST" onsubmit="returnFbChPermissionAndPreventDefaultAction();">
<script type="text/javascript">
var returnFbChPermissionAndPreventDefaultAction = function(){
//prevent default
if (event.preventDefault) {
event.preventDefault();
}
//specific for IE
valueOfreturn = fb_CheckPermission('publish_stream');
event.returnValue = valueOfreturn;
return event.returnValue ;
}
</script>

Categories

Resources