Submit form interfering with others - javascript

I have this email subscribe form for newsletter which gets delivered to me by email using PHP. It is located in footer which means that it is available on all pages across the website.
JSFIDDLE DEMO
Form works ok now but the problem is that it is interfering with other parts of website where forms are included - it messes those up and causes error to show on other fields as well.
My question is how do I isolate this form and script only for this part of the code so it will be defined only for this part of the webpage? What am I doing wrong?

As noted in the comments above,, you need to replace the "id" attributes in the html with "class" attributes. Then, modify your jQuery finders to search by class, constrained within the #subscribe form.
The HTML
<form id="subscribe" name="subscribe" action="#" method="post">
<input name="email" type="email" class="email" placeholder="Your e-mail adresss">
<span><button class="send" type="button">Subscribe</button></span>
</form>
And the Javascript
$(document).ready(function () {
$("#subscribe").submit(function () {
return false;
});
$("#subscribe .send").on("click", function () {
$('#subscribe input.error').removeClass('error');
var emailval = $("#subscribe .email").val();
var mailvalid = validateEmail(emailval);
if (mailvalid == false) {
$("#subscribe .email").addClass("error");
}
var minlen = $('#subscribe input[minlength]').filter(function(){
return this.value.length < +$(this).attr('minlength')
}).addClass('error').length;
if (mailvalid == true && minlen == 0) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<p><strong>Sending, please wait...</strong></p>");
$.ajax({
//you shouldn't need to change what you had here in the Fiddle; I didn't
//copy it for brevity's sake
});
}
});
});

Related

Want both PHP & JS form (empty fields/password match) validation?

I am designing an e-shop that allows profile registration. I need to have both Javascript & PHP validation for the registration form. (so when any of the fields are empty, I need to get a pop-up message that lets me know which specific field is empty + display on the screen beside the required field a visual message to advise the user where they need to correct the issue)
so far it is not working because my JS validation form activates onsubmit and my PHP is on action. I realize onsubmit activates before action and thus not allowing 'action' to go through.
I tried changing it from 'action' to 'onclick', but onsubmit also activates first and does not allow the PHP to work.
Here's my code for the form (I only included the first name portion so it won't get too long)
<form method="post" onclick="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="myForm" onsubmit="return validateForm()" style="border:1px solid #ccc">
<label><b>First Name</b></label>
<input type="text" name="firstName" placeholder="">
<?php echo $fnameErr;?>
<button type="submit" class="signupbtn" name="submit">Submit</button>
Here's my PHP code:
<?php
$fnameErr = "";
$fname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstName"])) {
$fnameErr = "Name is required";
}
else {
$fname = test_input($_POST["firstName"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I know the PHP code works, because if I delete the JS validation, it works as intended. I appreciate the help.
Please let me know if I need to add any extra information. Also, this hasn't been my first stop. I've been googling and trying to figure out how to fix this issue for hours to no avail...
This is the JS function being called (which also works as intended) this is also the shortened version to include only the name, the rest works the same, more if statements:
function validateForm() {
"use strict";
var fn = document.forms.myForm.firstName.value;
var ln = document.forms.myForm.lastName.value;
var em = document.forms.myForm.email.value;
var phone = document.forms.myForm.phone.value;
var pass = document.forms.myForm.psw.value;
var pass2 = document.forms.myForm.psw2.value;
if (fn === "") {
window.alert("First name must be filled out");
return false;
}
}
<input type="text" name="firstName" required>
You don't need any JavaScript.
Furthermore:
<form action="" method="post">
You don't need to specify the action if you're posting back to the current page. Using $_SERVER['PHP_SELF'] is potentially a vulnerability if you're not careful, and also breaks "pretty URLs" if you have them.
As said by #Niet The Dark Absol you can use the required but if you insist you can add e.preventdefault to prevent form from submitting in case of errors. We can elaborate properly if we can have a glimpse at your Javascript function.
You should change your onsubmit part and remove the onclick. Also your form is not valid as there is no action.
document.getElementById('myForm').addEventListener('submit',validateForm);
function validateForm(e) {
"use strict";
console.log(document.forms.myForm.firstName.value);
var fn = document.forms.myForm.firstName.value;
if (fn === "") {
window.alert("First name must be filled out");
e.preventDefault();
return false;
}
}
<form action="https://stackoverflow.com/" method="post" id="myForm">
<input type="text" name="firstName" >
<input type="submit">
</form>
There was a couple mistakes... But mainly what cause your problem is that onsubmit="return validateForm()". I also added e.preventDefault() it is to prevent the form submission if there is an error.

Google Invisible ReCaptcha not invisible

I just try to get Google Invisible ReCaptcha to work after submitting a form.
My problem is, the ReCaptcha is NOT invisible, it looks like the "old" recaptcha is popping up. I don't understand why. My site-key is for invisible recaptcha. Please help me.
First of all i'm loading the API:
<script src='https://www.google.com/recaptcha/api.js?render=explicit&onload=onScriptLoad' async defer></script>
My form looks like this:
<form method="post" id="contact-form-face" class="clearfix" onsubmit="return false">
<input type="text" required name="name" value="name" onFocus="if (this.value == 'name') this.value = '';" onBlur="if (this.value == '') this.value = 'name';" />
<button type="submit" id="sendButton" data-size="invisible" class="g-recaptcha contact_btn" onclick="onSubmitBtnClick()" value="send" >send</button>
</form>
JS:
window.onScriptLoad = function () {
// this callback will be called by recapcha/api.js once its loaded. If we used
// render=explicit as param in script src, then we can explicitly render reCaptcha at this point
// element to "render" invisible captcha in
var htmlEl = document.querySelector('.g-recaptcha');
// option to captcha
var captchaOptions = {
sitekey: 'XXXXXXX',
size: 'invisible',
// tell reCaptcha which callback to notify when user is successfully verified.
// if this value is string, then it must be name of function accessible via window['nameOfFunc'],
// and passing string is equivalent to specifying data-callback='nameOfFunc', but it can be
// reference to an actual function
callback: window.onUserVerified
};
// Only for "invisible" type. if true, will read value from html-element's data-* attribute if its not passed via captchaOptions
var inheritFromDataAttr = true;
console.log("render now!");
// now render
recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
};
// this is assigned from "data-callback" or render()'s "options.callback"
window.onUserVerified = function (token) {
alert('User Is verified');
console.log('token=', token);
};
// click handler for form's submit button
function onSubmitBtnClick () {
var token = window.grecaptcha.getResponse(recaptchaId);
// if no token, mean user is not validated yet
if (!token) {
// trigger validation
window.grecaptcha.execute(recaptchaId);
return;
}
var xhrData = {
'g-recaptcha-response': token
// more ajax body/data here
};
};
To make things clearer: This reCaptcha works fine, the callback loads, the verification works fine as well.... The only problem is, that this recaptcha must be invisibile, while it's not :/
I think your problem is that you are explicitly calling the render() method
recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
};
if you want it to be invisible, you have to include this custom DIV
<div class="g-recaptcha"
data-sitekey="your_site_key"
data-callback="onSubmit"
data-size="invisible">
</div>
https://developers.google.com/recaptcha/docs/invisible
the recaptcha script will look for the div class element and bind it there, then execute the call back when the recaptcha verification is invoked.
to invoke the recaptcha verification use grecaptcha.execute();
follow the example in the googledev page, is pretty straight forward.
I hope that helped =)
I think you are missing the badge parameter in your "captchaOptions".
there are 3 possible values : bottomright (default), bottomleft and inline (which lets you customize the css of the recaptcha).
Looking at the JavaScript API docs,
https://developers.google.com/recaptcha/docs/invisible#js_api
You need to add a div with an id to render to, the class and data attributes are not required on the button element when you render the captchas with JavaScript.
Your HTML should be:
<form method="post" id="contact-form-face" class="clearfix"
onsubmit="return false">
<input type="text" required name="name" value="name" onFocus="if
(this.value == 'name') this.value = '';" onBlur="if (this.value ==
'') this.value = 'name';" />
<div id="recaptcha"></div>
<button type="submit" id="sendButton" class="contact_btn"
onclick="onSubmitBtnClick()"value="send">send</button>
</form>
And Your JS should be updated to:
// element to "render" invisible captcha in
var htmlEl = 'recaptcha'

HTML Form: How to remember text values of button click?

If you have a form, type some text into it, and press the Enter key, whenever revisiting that form you can double-click on the input box and see the past text submissions.
I have a site that when you press Enter OR click a button, it should take whatever is in the text box and use it for data processing.
This works totally fine when not surrounded by a form but when surrounded by a form an you press the Enter key, it does not act as an enter button push, I believe it's being overridden by the form.
My goal is to have the user be able to press the Enter key as well as click the button to submit the data, but to also remember the text values that were in the text box regardless of which way you submitted the data.
What I have:
<input type="text" id="username-field" class="form-control" placeholder="username">
<input class="btn btn-default" type="button" id="get-name" value="Get Name">
Javascript
$("#get-name").click(function() {
var name = $("#username-field").val();
// ... call other function with name ...
});
$("#get-name").keydown(function(e) {
if (e.which == 13) {
var name = $("#username-field").val();
// ... call other function with name ...
}
");
What I would like to use:
<form>
<input type="text" id="username-field" class="form-control" placeholder="username">
</form>
I tried doing e.preventDefault() when the Enter key is pressed, but this does not remember the text in the input field.
I also considered doing a small cache type thing but am unsure of how I'd go about this.
Any help would be much appreciated!
Thanks!
Doesn't use form at all. Just, why you added it, if you don't use it as intended?
You either mistyped provided code copy-paste, or have errors in yours script (the $("#get-name").val() mistake).
If you want to prevent form from submission, you should e.preventDefault()-it in submission handler, and return false from it:
$('#form-id').submit(function (e) {
e.preventDefault();
// do smth. else here
...
return false;
})
Saving/retriving data with localStorage for HTML5-supporting browsers:
$(function () {
$('form input[type=text]').doubleclick(function () {
var id = $(this).attr("id");
value = localStorage.getItem("form_xxx_" + id);
// do smth. with cached value, ie:
if (value != "")
$(this).val(value); // put in textfield
});
});
$('form').submit(function (e) {
$('form input[type=text]').each(function () {
var id = $(this).attr("id");
localStorage.setItem("form_xxx_" + id, $(this).val());
});
...
// all other work
});
Note: make sure you don't put some user's personal data in browser's local storage -_-

Check if textbox contains text, if it does then send

I have this email form, with "Sender, "Subject" and "Message".
But i haven't linked it to make sure they have written something, so if someone press the "Send" button without typing anyting, i get a blank email. So i want it to abort the email sending if the textbox is empty, and send it if it contains any text.
code for the send button:
<input type="submit" name="submit" value="Submit" class="submit-button" />
ID for the textbox is: textbox_text
You can use jquery to validate the form like this-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
Sender
<input type="text">
<br/>Subject
<input type="text">
<br/>Message
<input type="text" id="txtMessage">
<br/>
<input type="submit" value="Send" name="btnSend">
</form>
<script type="text/javascript">
$(document).ready(function() {
$("input[name=btnSend]").click(function() {
var msg = $("#txtMessage").val();
if (msg == "") {
alert("Please enter the message");
return false;
}
});
});
</script>
Java Script function
<script type="text/javascript">
function IsEmpty()
{
if(document.forms['frm'].textbox_text.value == "")
{
alert('Message body is empty');
return false;
}
return true;
}
</script>
HTML
<form name="frm">
<input type="submit" name="submit" onclick="return IsEmpty();" value="Submit" class="submit-button" />
</form>
EDIT Check textbox2 in if condition
if(document.forms['frm'].textbox1.value == "" && document.forms['frm'].textbox2.value == "")
I dont know this is your exact answer but it will helps you to validate:
$('#checkSubmit').click(function(){
var chec=$("#textContent").val();
if(chec=="")
alert("Please add your content");
else
alert("successfully submitted");
});
check out this fiddle:
http://jsfiddle.net/0t3oovoa/
You need to check that on server side (with php) and you can also check it on client side(Javascript).
Client side test is good if you want the user to get fast response, but you still need to check it on server side because javascript on your website can ALWAYS be changed by user.
You could also just add "required" on your input elements.
for server side check with php:
<?php
//Check if variables exist
if(isset($_POST['sender']) && isset($_POST['subject']) && isset($_POST['message'])){
//Check if sender value is empty
if(empty($_POST['sender'])){
//If empty, go back to form.Display error with $_GET['error'] in your form page
header('location: backToFormPage.php?error=send');
}
//...
}
//Variables doesn't exist
else{
//Redirect to page or other action
}
?>
You can achieve it two ways:
1. Client Side( Which i recommend) use the form validation to validate the form data if it is empty tell them to fill it. You chose the submit button to trigger validation that is not recommended instead validation is triggered on form submission or on change of input elements(for real-time validation). Anyways below is an example for validation using the click event on submit button.
var validateTextBox = function(textBox) {
var val = textBox.value;
if(val=="") { // Check for empty textbox
return false;
}
return true;
}
documnet.querySelector('#SubmitButton').onclick(function () {
var textbox = document.querySelector("#SubjectORMessage").value;
if(validateTextBox(textbox)){
// Do something to let page know that form is valid
} else {
// Let the user know that he has done something wrong
alert("Please fill the content");
}
})
2. Server Side if unfortunately empty data is send to the server, then use server side validation (Server side validation requires a little more thing to do at more than one place, i.e., html, php/python/perl)

Prevent action attribute from running php script with javascript [duplicate]

This question already has answers here:
prevent form from POSTing until javascript code is satisfied
(4 answers)
Closed 9 years ago.
Is there a way that I can use javascript to prevent a form from runing a php script. For example something like this:
<form action="somePage.php" method="POST>
<input type= "text" class= "field" name = "blah">
<input type="submit" value="Send" >
</form>
I know how to validate what's in that text box using javascript, but I want to prevent the somePage.php to run if the text box is empty. I haven't really tried anything cause I just don't know how to do it.
Hope you guys understand my problem.
Thanks
You can attach function to submit event of the form:
document.getElementById('form-id').addEventListener("submit", function(e){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null){
e.preventDefault();
alert('Pls fill the required fields.');
return;
}
return true;
});
OR
Below solution uses inline js:
If you want to run your js function before submitting the form to php script, you can use onsubmit attribute of the form,
<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">
<input type= "text" class= "field" id="field1" name = "blah">
<input type="submit" value="Send" >
</form>
In formSubmit function you can check the value of the input, if its empty or not, and if empty, then you can just return false;
var formSubmit = function(){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null)
return false;
else
return true;
}
You simply need to return false for your submit event by grabbing the form (I used querySelector because you have no IDs or classes), and adding a submit listening event to return false.
var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
return false;
});
Use this code to prevent form from submitting:
var first_form = document.getElementsByTagName('form')[0];
first_form.addEventListener('submit', function (e) {
e.preventDefault(); //This actually prevent browser default behaviour
alert('Don\'t submit');
//Do your stuff here
}, false);
Better read docs
you could in your somePage.php have this be a clause somewhere new the beggin:
if(empty($_POST['blah'])){
die();
}
or the inverse of
if(!empty($_POST['blah'])){
//do what this php is supposed to
}
else{
//display error
}
this will prevent your php from running if that field is not filled out.
Personally I return them to the same page setting some error on the page.

Categories