AJAX Login form not working - javascript

I have the following ajax script and form to login to my website:
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
<script>
$.ajax({
type: "post",
url: "/doLogin",
data: $('#login').serialize(),
success: function(result) {
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either your username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
but it doesn't preform the ajax, and brings me to the result page, which is not what I want. Is there any specific reason that the AJAX is not working? I'm kind of new to JavaScript so sorry if this is obvious.

You are running the Ajax function as soon as the script loads, and not doing anything to prevent the form from submitting normally when the form submits.
You need to move the JS you have already into a function. Then bind that function as a submit handler on the form. Then prevent the default behaviour of the submit event.
$('#login').on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: this.action,
data: $(this).serialize(),
success: function(result) {
if (result == " success") {
window.location = "/index.php";
} else if (result == " failure") {
$("#alert").html("<div class='alert alert-warning'>Either your username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
<form action="/doLogin" method="post" id='#login'>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<label for="email" class="input-group-addon">E-Mail</label>
<input type="email" class="form-control" name="email" id="email" value="" />
<br />
</div>
<div class="input-group">
<label class="input-group-addon" for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form>
</div>
That said - when you successfully login, you just redirect to another page. You are almost certainly better off not using Ajax at all for this.

The following link may be helpful if you are new to ajax
http://webdevelopingcat.com/jquery-php-beginner-tutorial-ajax/

login should be the form id but you did not post your form opening tag
<form id = "login">
and in your ajax code you should handle the submit event of the form like this:
$("#login").submit(function({ // your logic should be here
}))

Related

Undefine showing in $.ajax at mouse over when debugging and value not pass

I am trying to get my values from a field by ajax but ajax don't work and when I debug it in Firefox then at $.ajax is showing undefined.
Check this link please for my browser debug option http://prntscr.com/m8xnxy
$(document).ready(function() {
$("#add").click(function() {
var search = $("#names").val();
$.ajax({
type: "POST",
url: "http://localhost/ajax/shakil.php",
data: { search: search },
success: function(data) {
alert(data);
}
});
});
});
<form class="col-sm-4">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input
type="text"
class="form-control"
id="names"
aria-describedby="emailHelp"
placeholder="Enter email"
/>
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<button type="submit" class="btn btn-primary" id="add" name="submit">
Submit
</button>
</form>

Prevent default not working in ajax form submit

I tried my level best in implementing this ajax. I dont what the form's default action to happen.I give prevent default but its not working. My page form is getting submitted without ajax. When i tried on click instead of on submit the captcha validation is not working.Can someone tell whats the mistake here. Thanks in advance.
$(document).ready(function() {
$("#login").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
success: function(data) {
alert(data);
if (data == 'success') {
location.reload();
} else {
$('#loginmsg').html(data).fadeIn('slow');
}
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form action="<?php echo $root ?>login.php" id="login" method="post">
<div id="loginmsg"></div>
<div class="form-group">
<label for="login_email" class="sr-only">Email address</label>
<input name="email" type="email" class="form-control" id="login_email" placeholder="Email address">
</div>
<div class="form-group">
<label for="login_password" class="sr-only">Password</label>
<input name="password" type="password" class="form-control" id="login_password" placeholder="Password">
</div>
<div class="form-group">
<img src="common/captcha/captcha.php" id="captcha" height="50" />
<i class="fa fa-refresh refresh-sec"></i>
<div class="form-item inline">
<div class="captcha-block">
<p class="comment-form-captcha"><input name="captcha" type="text" id="captcha-form" autocomplete="off" class="form-text contact-captcha" maxlength="6" required="required" /></p>
</div>
</div>
</div>
<div class="text-center">
<button type="submit" class="theme_button color1">
Log in
</button>
</div>
</form>
you should use
<button type="button" class="theme_button color1">Log in</button>
instead of
<button type="submit" class="theme_button color1">Log in</button>
and change the form submit to
$(document).on("click",".theme_button ", function(){
});
you have two id in your html
<a class="topline-button" id="login" data-target="#" href="./" data-toggle="dropdown" aria-haspopup="true" role="button" aria-expanded="false">
<i class="fa fa-lock" aria-hidden="true"></i> Login
</a>
<form role="form" action="login.php" id="login" method="post">
</form>
You can try this
$(document).ready(function() {
$(document).on('click','#login' ,function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
success: function(data) {
alert(data);
if (data == 'success') {
location.reload();
} else {
$('#loginmsg').html(data).fadeIn('slow');
}
}
});
});
});

Two AJAX form submissions in a single JS file, only one is working

In the HTML, the forms look identical, just the form ID is changed. I use this JS file to submit the forms using AJAX:
$("#change-password").submit(function(e) {
var url = "http://domain/actions";
$.ajax({
type: "POST",
url: url,
data: $("#change-password").serialize(),
success: function(data) {
$("div.change-password-response").html(data);
}
});
e.preventDefault();
});
$("#change-email").submit(function(e) {
var url = "http://domain/actions";
$.ajax({
type: "POST",
url: url,
data: $("#change-email").serialize(),
success: function(data) {
$("div.change-email-response").html(data);
}
});
e.preventDefault();
});
HTML Part
<div class="col-md-6 col-sm-6 add_bottom_30">
<h4>Schimbare parola</h4>
<form id="change-password" method="post">
<div class="form-group">
<label>Parola veche</label>
<input class="form-control" name="old_password" id="old_password" type="password" autocomplete="off">
</div>
<div class="form-group">
<label>Parola noua</label>
<input class="form-control" name="new_password" id="new_password" type="password" autocomplete="off">
</div>
<div class="form-group">
<label>Confirma parola noua</label>
<input class="form-control" name="confirm_new_password" id="confirm_new_password" type="password" autocomplete="off">
</div>
<input type="hidden" name="action" value="change-password">
<button type="submit" class="btn_1 green">Actualizeaza parola</button>
<div class="change-password-response form-response"></div>
</form>
</div>
<div class="col-md-6 col-sm-6 add_bottom_30">
<h4>Schimbare adresa email</h4>
<form id="change-email" method="post">
<div class="form-group">
<label>Email vechi</label>
<input class="form-control" name="old_email" id="old_email" type="text" autocomplete="off">
</div>
<div class="form-group">
<label>Email nou</label>
<input class="form-control" name="new_email" id="new_email" type="text" autocomplete="off">
</div>
<div class="form-group">
<label>Confirma email nou</label>
<input class="form-control" name="confirm_new_email" id="confirm_new_email" type="password" autocomplete="off">
</div>
<input type="hidden" name="action" value="change-email">
<button type="submit" class="btn_1 green">Actualizeaza Email</button>
<div class="change-email-response form-response"></div>
</form>
</div>
Now, my problem is that Form 1 is working, Form 2 is not triggering the AJAX and works as normal form. What am I doing wrong?
Check if #change-email has other binded events.
In Firebug, inspect #change-email element and go to Event tab.
In Chrome, inspect that element and go to Event Listeners tab.
You will see all binded events and corresponded callback functions.
If it will not help, try to submit a form manually from Console
Inspect a form, then run
$($0).submit();
If it will work, looks like you have some events on you button.

ajax form not submitting handler expecting submit name attribute

I'm having a little problem getting a form to submit via ajax. I think it's one of two problems:
leads.py (which I am able to view, but do not have the ability to modify) is expecting a submit input name of name="submitButtonName" and because I am using e.preventDefault(); to disable normal form submitting the form is not being handled by the handler when submitted.
It could be possibly that the data being serialized is wrong, when i output it to console it looks like this which appears to be duplicated:
first_name=Frank&last_name=TheTank&email_addr=frank%40thetank.com&remarks=&first_name=Frank&last_name=TheTank&email_addr=frank%40thetank.com
any suggestions?
here is the full script:
<!-- Defines element markup -->
<dom-module id="landing-modal">
<template>
<div id="landing-modal" class="modal hide fade" tabindex="-1" role="dialog">
<div class="modal-body">
<p class=lead>
To view this listing, please provide us with some basic contact information...
</p>
<form class="form-horizontal lead-form" method="post" action="/leads/buy">
<div class="control-group">
<label class="control-label">Required Information</label>
</div>
<div class="control-group">
<label class="control-label">First Name</label>
<div class="controls">
<input type="text" name="first_name" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<label class="control-label">Last Name</label>
<div class="controls">
<input type="text" name="last_name" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<label class="control-label">Email</label>
<div class="controls">
<input type="email" name="email_addr" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<div class="controls">
<input style="display:none;" type="text" name="remarks" value="" />
<input type="reset" value="Reset" name="reset" class="btn">
<input class="btn btn-primary" type="submit" name="submitButtonName" value="Submit" />
</div>
</div>
</form>
</div>
</div>
</template>
<script>
$(document).on('submit', '.lead-form', function(e) {
$.ajax({
url: $('.lead-form').attr('action'), //gets the action url
type: $('.lead-form').attr('method'), //gets the form method post
data: $('.lead-form').serialize(), //creates the form submit date eg. FirstName=Mickey&LastName=Mouse
success: function(html) {
console.log($('.lead-form').serialize());
}
});
e.preventDefault(); //prevents the submit input from being submitted normally
});
Polymer({
is: 'landing-modal',
created: function() {},
ready: function() {},
attached: function() {},
detached: function() {},
attributeChanged: function(name, type) {}
});
</script>
</dom-module>
edit::
I tried to add
<input type="hidden" name="submitButtonName" />
<input class="btn btn-primary" type="submit" name="submit" value="Submit" />
which results in a 500 error in console
server side code:
if "submitButtonName" in kwargs:
errors = []
if not kwargs['first_name']:
errors.append("Please enter your first name.")
if not kwargs['last_name']:
errors.append("Please enter your last name.")
if not kwargs['email_addr']:
errors.append("Please enter your email address.")
if errors:
error_msg = "<ul>" + "".join([
"<li>"+x for x in errors
]) + "</ul>"
result['error_msg'] = error_msg
else:
save = True
if save:
# 'remarks' is an invisible field that can only get filled in by
# spam bots, so if there's a value in it, ignore the submission.
if kwargs['remarks']:
import sys
sys.stderr.write("Ignoring spam submission: %r\n" % ([mode,kwargs],))
else:
self.save_form(mode, kwargs)
raise cherrypy.InternalRedirect("/leads/thankyou/"+mode)
result.update(self.form.render(values))
if mode=="C":
result.update(self.cmaform.render(values))
if mode=="E":
result.update(self.contactform.render(values))
return result

How to execute ajax post after execution of form validation on form submit?

I have an ajax post call which submits a contact form in my Rails application.
function contact_email(e){
form = $('form');
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize(),
dataType: "JSON",
async: false,
success: function(data) {
window.location = data.redirect_url;
},
error: function(xhr, status) {
console.log(status);
}
});
return false;
}
And the accompanying html is :
<div class="form-container">
<form name="contact_form" action="/contact" data-remote="true" class="forms" >
<fieldset>
<ol>
<li class="form-row text-input-row name-field">
<input type="text" name="name" class="text-input defaultText required" title="Name (Required)"/>
</li>
<li class="form-row text-input-row email-field">
<input type="text" name="email" class="text-input defaultText required email" title="Email (Required)"/>
</li>
<li class="form-row text-input-row subject-field">
<input type="text" name="subject" class="text-input defaultText" title="Subject"/>
</li>
<li class="form-row text-area-row">
<textarea name="message" class="text-area required"></textarea>
</li>
<li class="form-row hidden-row">
<input type="hidden" name="hidden" value="" />
</li>
<li class="button-row">
<input onclick="contact_email()" type="submit" value="Submit" name="submit" class="btn btn-submit bm0" />
</li>
</ol>
<input type="hidden" name="v_error" id="v-error" value="Required" />
<input type="hidden" name="v_email" id="v-email" value="Enter a valid email" />
</fieldset>
</form>
</div>
Jquery.slickforms is being used to validate the forms before submission, which essentially checks to see if required fields are filled in and does regex validation on the email provided.
Slick forms is initiated by:
jQuery(document).ready(function ($) {
$('.forms').dcSlickForms();
});
However, when debugging the execution, my
onclick="contact_email()"
is first evaluated and a POST is made, and AFTER that only does the execution of the slickforms validation occur. How can I make it such that the contact_email() function I've bound to onsubmit occurs if and only after successful form validation by slickforms?

Categories

Resources