Trying to Stop Button From Auto-Submitting With Page Load - javascript

I have a page with a series of inputs, similar to a form but not. Upon pressing Submit, I want to run my function submitForm(). However, every time the page loads, it auto-clicks submit. Any ideas on how to stop this from happening?
JS:
function submitForm(){
// Initiate Variables With Form Content
var fname = document.getElementById(name).value();
var femail = document.getElementById(email).value();
var fmessage = document.getElementById(message).value();
$.ajax({
type: "POST",
url: "cgi-bin/process.php",
data: "name=" + fname + "&email=" + femail + "&message=" + fmessage,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
}
function formSuccess(){
$( "#msgSubmit" ).removeClass( "hidden" );
}
$(function() {
$("#btnContact").on("click", submitForm());
});
Any my HTML:
<div class="row">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name"
required="">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter email"
required="">
<label for="message" class="h4 ">Message</label>
<textarea id="message" class="form-control" rows="5" placeholder="Enter your message"
required=""></textarea>
</div>
<button id="btnContact" type="submit">Send Message</button>
<div id="msgSubmit" class="h3 text-center hidden">Message Submitted!</div>
</div>

Remove the () from your final statement.
s/submitForm\(\)/submitForm/.
You are actually calling the function.
http://jsfiddle.net/fx6hefe4/
Will look like this:
$(function() {
$("#btnContact").on("click", submitForm);
});

Working fiddle.
Your code work after several changes.
Replace :
var fname = document.getElementById(name).value();
var femail = document.getElementById(email).value();
var fmessage = document.getElementById(message).value();
By :
var fname = document.getElementById('name').value;
var femail = document.getElementById('email').value;
var fmessage = document.getElementById('message').value;
Replace :
$("#btnContact").on("click", submitForm());
By :
$("#btnContact").on("click", function(){
submitForm();
});
Replace :
<button id="btnContact" type="submit">Send Message</button>
By :
<button id="btnContact" type="button">Send Message</button>
Hope this helps.

Related

jQuery and AJAX work only once

I have problem with AJAX and jQuery. I write function for login to system, but it works only first time. Here is my code:
html in modal:
<form role="form" onsubmit=" return login()" method="post" action="" >
<div class="form-group">
<label for="userName"><span class="glyphicon glyphicon-user"></span>E-mail</label>
<input type="email" name="emailLogin" class="form-control" id="userName" placeholder="e-mail" required>
</div>
<div class="form-group">
<label for="password"><span class="glyphicon glyphicon-eye-open"><span>Password</label>
<input type="password" name="passLogin" class="form-control" id="password" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Login<span class="glyphicon glyphicon-log-in"></span></button>
</form>
here is jquery:
function login(){
login=document.getElementById('userName').value;
pass=document.getElementById('password').value;
var dataString="emailLogin="+login+"&passLogin="+pass;
$.ajax({
type: "POST",
url: "models/handler/KlientHandler.php",
cache: false,
data: dataString,
success: function(text){
if(text=='0'){
$("#loginError").removeClass('hidden');
}else{
$("#loginOk").removeClass('hidden');
$("#myModal").modal('hide');
$("#loginLi").html("<a id=\"user\">"+login+" (Profile)<span class=\"glyphicon glyphicon-user\"></span></a>");
$("#regLi").html(""+login+" (Logout)<span class=\"glyphicon glyphicon-log-out\"></span>");
}
}
});
return false;
}
You are overwriting your login function with a string.
function foo() {
alert('foo');
foo = function () {
alert('bar');
}
}
<a onclick="foo()">
click me!
</a>
See how the second click here causes a different alert? In your case you're replacing the function with a string instead of a function, causing a syntax error. Don't forget to var your variables.
var login=document.getElementById('userName').value;
var pass=document.getElementById('password').value;
The snippet tests your logic and there was a console error for your login and pass variables. I set them as 'var' and put your success logic in the 'error' section of the ajax request since I cannot reach your server, but it does create the logout button. Is that what you wanted?
function login() {
var login = document.getElementById('userName').value;
var pass = document.getElementById('password').value;
var dataString = "emailLogin=" + login + "&passLogin=" + pass;
$.ajax({
type: "POST",
url: "models/handler/KlientHandler.php",
cache: false,
data: dataString,
success: function(text) {
/* Success logic */
},
error: function() {
alert('Test - success logic');
$("#loginOk").removeClass('hidden');
//$("#myModal").modal('hide');
$("#loginLi").html("<a id=\"user\">" + login + " (Profile)<span class=\"glyphicon glyphicon-user\"></span></a>");
$("#regLi").html("" + login + " (Logout)<span class=\"glyphicon glyphicon-log-out\"></span>");
}
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" onsubmit=" return login()" method="post" action="" >
<div class="form-group">
<label for="userName"><span class="glyphicon glyphicon-user"></span>E-mail</label>
<input type="email" name="emailLogin" class="form-control" id="userName" placeholder="e-mail" required>
</div>
<div class="form-group">
<label for="password"><span class="glyphicon glyphicon-eye-open"><span>Password</label>
<input type="password" name="passLogin" class="form-control" id="password" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Login<span class="glyphicon glyphicon-log-in"></span></button>
</form>
<div id="loginLi"></div>
<div id="regLi"></div>
<div id="loginOk">Login OK</div>

Form elements values not getting stored in javascript variables

I have been learning javascript by building some mockup website while doing so an error popped up where the form elements are not getting stored to my javascript variables.I have inserted my HTML code of modal dialog box that contains the form and the JS code.Can anyone suggest me where I am going wrong?
document.getElementById("sub").addEventListener("click",store());
function store(){
var userName = document.getElementById("nme").value;
var emailId = document.getElementById("mail").value;
var password = document.getElementById("pd").value;
var rpassword = document.getElementById("rpd").value;
console.log(userName);
if (password !== rpassword){
alert("your password doesn't match");
}
else{
localStorage.setItem("name",userName.value);
localStorage.setItem("email",emailId.value);
localStorage.setItem("password",password.value);
}
}
<div class=row>
<form class="col-xs-12" method="post">
<div class="form-group">
<input type="text" class="form-control form-design input-lg enable" id="nme" name="user" placeholder="UserName">
<input type="text" class="form-control input-lg enable" id="mail" name="mail" placeholder="Email-Id">
</div>
<div class="form-group">
<input type="password" class="form-control form-design input-lg enable" id="pd" name="pwd" placeholder="Password">
<input type="password" class="form-control input-lg enable" name="rpwd" id="rpds" placeholder="Retype Password">
<input type="submit" id="sub" class="btn btn-block btn-lg navi-style lnk" value="SignUp">
</div>
</form>
</div>
<footer class="align">Already a member?<a class="newlnk" data-toggle="modal" href="#login">SignIn</a>
</footer>
</div>
<!--body closed-->
</div>
<!--content closed-->
</div>
<!--Dialog box closed-->
</div>
<!--Model closed-->
</div>
<!--container closed-->
The variables to store should be of type string i.e. var userName should already be a string, so storing userName.value will result in trying to store 'undefined', hence the correct values to store should be the var without the 'value' property and one of your element ids is misspeled i.e.
var rpassword = document.getElementById("rpds").value;
.
e.g. try the following code instead of the current store function
function store(){
var userName = document.getElementById("nme").value;
var emailId = document.getElementById("mail").value;
var password = document.getElementById("pd").value;
var rpassword = document.getElementById("rpds").value;
console.log(userName);
if (password !== rpassword){
alert("your password doesn't match");
}
else{
localStorage.setItem("name",userName);
localStorage.setItem("email",emailId);
localStorage.setItem("password",password);
}
}
You are trying to store userName.value instead of userName (and so on).
Also, you add an event listener but actually call the function store instead of referencing it.
document.getElementById("sub").addEventListener("click",store);
function store(){
var userName = document.getElementById("nme").value;
var emailId = document.getElementById("mail").value;
var password = document.getElementById("pd").value;
var rpassword = document.getElementById("rpd").value;
console.log(userName);
if (password !== rpassword){
alert("your password doesn't match");
}
else{
localStorage.setItem("name",userName);
localStorage.setItem("email",emailId);
localStorage.setItem("password",password);
}
}

Submit form with ajax via callback

I want to submit the form when a gcapcha was clicked. I tried submit with (my silly) jquery function that I know. But it's not work.
Here is my code (what's wrong with it).
Javascript
var verifyCallback = function(e) {
document.getElementById("form-contact").submit();
$.ajax({
type : 'POST',
url : 'inc/contact_sent.php',
data : $(this).serialize(),
success : function(data){
$("#contact").html(data);
}
});
return false;
};
var onloadCallback = function() {
grecaptcha.render("captcha", {
sitekey: "xxx",
callback: verifyCallback
})
};
HTML
<div id="contact" class="contact-form">
<form class="ajaxForm detailedsearch inline-style" method="post" id="form-contact">
<input type="text" class="form-control" name="cntc_name" placeholder="Your name" required>
<input type="email" class="form-control" name="cntc_email" placeholder="Your email" required>
<input type="text" class="form-control" name="cntc_tel" placeholder="Your phone">
<input type="text" class="form-control" name="cntc_subj" placeholder="Subject" value="<?=(isset($_POST['ptitle']))?"Queries for $_POST[ptitle]":""?>" required>
<textarea class="form-control" name="cntc_desc" rows="6" placeholder="Your Detail" required></textarea>
<div class="form-group">
<div id="captcha" class="center-captcha"></div>
<div id="gcaptcha" style="transform:scale(0.50);-webkit-transform:scale(0.50);transform-origin:0 0;-webkit-transform-origin:0 0;"></div>
<span class="text-danger">*Please complete the form to proceed.</span>
</div>
<!-- <button type="submit" class="btn btn-success btn-block"><i class="fa fa-envelope-o"></i> Submit Form</button> -->
</form>
</div>
You should do this....
//register a event for form submit
$( "form" ).submit(function( e ) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'inc/contact_sent.php',
data : $(this).serialize(), //serialize the form data
success : function(data){
$("#contact").html(data);
}
});
});
var verifyCallback = function(e) {
//submit form
$("#form-contact").submit();
return false;
};
var onloadCallback = function() {
grecaptcha.render("captcha", {
sitekey: "xxx",
callback: verifyCallback
})
};

jQuery not recoqnizing form and page refreshes

I have a form that needs to be submitted and the data sent to mysql with Ajax and jQuery, however when clicking submit, the page refreshes and the jQuery code is not running.
Here is my HTML code:
<form class="form-horizontal" role="form" action="" method="post">
<input type="text" id="firstname" class="form-control" placeholder="Firstname" required=""></br>
<input type="text" id="lastname" class="form-control" placeholder="Lastname" required=""></br>
<input type="text" id="signup_email" class="form-control" placeholder="Email address" required=""></br>
<select id="gender" class="form-control">
<option>Select Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select></br>
<input type="password" id="signup_password" class="form-control" placeholder="Password" required="">
<input type="submit" id="signup_button" name="signup_button" class="btn btn-primary" value="Sign up">
</form>
And here is my jQuery:
<script type="text/javascript">
$(function()){
$("#signup_button").click(function() {
var firstname = $("input#firstname").val();
var lastname = $("input#lastname").val();
var email = $("input#signup_email").val();
var gender = $("select#gender").val();
var password = $("input#signup_password").val();
var datastring = 'new=yes'+'&firstname='+firstname+'&lastname='+lastname'&email='+email+'&gender='+gender+'&password='+password;
$.ajax({
type:"POST";
url:"api/signup.php";
data: datastring;
cache: true;
success: function(html) {
$.("#alert_succes_congrats").css('display', '');
}
})
return false;
})
}
</script>
Thank you.
You have two options to solve your problem:
1st option:
Change
<input type="submit" id="signup_button" name="signup_button" class="btn btn-primary" value="Sign up">
To
<input type="button" id="signup_button" name="signup_button" class="btn btn-primary" value="Sign up">
So the button will not trigger a form submit.
2nd option:
Put an event.preventDefault at your click handler.
$("#signup_button").click(function(event) {
/* Your stuff */
event.preventDefault();
}
So it will not trigger browser default action to form submit button.
You code has lot of syntax error:
$(function()){
Should be
$(function(){
Plus the ajax members should be separated by comma and not semi-colon, there was issue in string concatenation as well. Next time this happens, please check the browser console for any javascript issues.
This should work
<script type="text/javascript">
$(function(){
$("#signup_button").click(function() {
var firstname = $("input#firstname").val();
var lastname = $("input#lastname").val();
var email = $("input#signup_email").val();
var gender = $("select#gender").val();
var password = $("input#signup_password").val();
var datastring = 'new=yes'+'&firstname='+firstname+'&lastname='+lastname+'&email='+email+'&gender='+gender+'&password='+password;
$.ajax({
type:"POST",
url:"api/signup.php",
data: datastring,
cache: true,
success: function(html) {
$("#alert_succes_congrats").css('display', '');
}
});
return false;
});
});

Check if form is completed before activating submit button

I am creating a form where a user has to fill out several fields and then click sign up. However, I want JavaScript to check if the passwords match, and if they don't or a field is left empty to put the signup button into a disabled state with Bootstrap. However, nothing is working. Here is my code:
JSFIDDLE: http://jsfiddle.net/jbe65/
echo '
<h3>Don\'t have an account yet? Sign up now!</h3>
<form action="signup.php" method="post">
<input type="text" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass">
<input type="password" class="form-control" placeholder="Again" name="passver" id="passver">
<br><br>
<p id="submit">button class="btn btn-primary btn-block" type="submit">Sign Up/button></p>
</form>
<script>
var empty = "";
var email = $(\'#email\').val()\;
var pass = $(\'#pass\').val()\;
var passver = $(\'#passver\').val()\;
if (empty == email)
{
if (pass != passver)
{
document.getElementById("submit").innerHTML=\'<button class="btn btn-primary btn-block" type="submit" disabled="disabled">Sign Up</button>\';
}
}
</script>
';
I will suggest make the button lookalike disable (by css) and once all the cond pass can make it enable (by css)..
$(document).ready(function () {
$("#formid").on("submit", function (e) {
var empty = "";
var email = $('#email').val();
var pass = $('#pass').val();
var passver = $('#passver').val();
if (empty == email || pass !== passver)
{
alert("please enter valid email and password.");
e.preventDefault();
}
else
{
//u can call this in textbox blur also...
$("#sub").removeClass("disable");
}
});
});
Fiddle Demo
I'm assuming you are using PHP. If so, you can replace the echo statement with a closing PHP bracket ?> to escape the parser. It's generally easier to deal with.
To answer the question at hand, since you are using jQuery, there is no need to change the innerHTML of the p tag, just use the .prop() function, like so:
?>
<h3>Don't have an account yet? Sign up now!</h3>
<form action="signup.php" method="post">
<input type="text" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass">
<input type="password" class="form-control" placeholder="Again" name="passver" id="passver">
<p id="submit"><button class="btn btn-primary btn-block" type="submit">Sign Up</button></p>
</form>
<script>
var email = $('#email').val();
var pass = $('#pass').val();
var passver = $('#passver').val();
if ("" == email)
{
if (pass != passver)
{
$('#submit button').prop('disabled', true);
}
}
</script>
<?php
If you're using HTML5 , Put "Required" and then the submit button will not be loaded if there is an empty field Ex :

Categories

Resources