jQuery ajax second post - javascript

When I hit the submit button at the first time these codes works. But when I hit the second time to the button even if email and password values were true nothing happens and the user can not login. But if I write the true values at the first time, it works and user can login. So I figured the cause of this problem is about the "return false;" phrase. But if I remove return false; phrase, the form posts and ajax codes become useless. I must avoid the posting without ajax.
jQuery:
<script>
$(document).ready(function(){
$('#submit-btn').click(function(){
var email = $('#email').val();
email = $.trim(email);
var password = $('#password').val();
password = $.trim(password);
if(email == "") {
$('#email').css({
"background-color": "#FF7070"
});
$('#box1').css({
"visibility": "visible"
});
return false;
}else if(password == "") {
$('#password').css({
"background-color": "#FF7070"
});
$('#box2').css({
"visibility": "visible"
});
return false;
}else{
$.ajax({
type: "POST",
url: "ajax.php",
data: $('#loginform').serialize(),
timeout: 5000,
success: function(c) {
if(c == "no") {
$('#box3').css({
"visibility": "visible"
});
return false;
} else if (c == "ok") {
window.location.href = "homepage.php";
}
},
error: function(a, b) {
if (b == "timeout") {
alert("Error: #101");
}
},
statusCode: {
404: function(){
alert("Error: #102")
}
}
});
}
return false;
})
});
</script>
Html:
<form name="loginform" id="loginform" method="post" action="">
<div class="field">
<input type="text" maxlength="40" id="email" name="email" placeholder="E-mail">
</div>
<div class="field">
<input type="password" id="password" name="password" placeholder="Password" autocomplete="off">
</div>
<div class="field">
<input type="submit" id="submit-btn" value="Log in">
</div>
<div class="keep-login">
<label for="remember">
<input type="checkbox" name="remember" id="remember" checked="checked">Remember me
</label>
<span>Forgot password?</span>
</div>
</form>
PHP:
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'email' => array('required' => true),
'password' => array('required' => true)
));
if($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('email'), Input::get('password'), $remember);
if($login) {
echo "ok";
} else {
echo "no";
}
} else {
echo "no";
}
}
}

First, remove the method and action attributes of the form element. You can remove the form tag altogether but if you want to support non-javascript submissions, you'll need the form tag (however, the original question did not ask for this). You're 'submitting' the form via jQuery, so you don't need a method and an action on a form tag.
Input type="password" never autocompletes, so you don't need that attribute.
I also added an error div. Here is your new html:
<div id="error" style="display: none;">Login failed.</div>
<form>
<div class="field">
<input type="text" maxlength="40" id="email" name="email" placeholder="E-mail">
</div>
<div class="field">
<input type="password" id="password" name="password" placeholder="Password">
</div>
<div class="field">
<input type="submit" id="submit-btn" value="Log in">
</div>
<div class="keep-login">
<label for="remember">
<input type="checkbox" name="remember" id="remember" checked="checked">Remember me
</label>
<span>Forgot password?</span>
</div>
</form>
Replace your $.ajax statement with a $.post statement, and simply your logic.
$.post("ajax.php", { e: email, p: password }, function (data) {
if (data == "ok") window.location.href = "homepage.php";
else $("#error").slideDown().delay(3000).slideUp(); // I added div#error with "Failed to Login" message in the html above
});
This code will now redirect if the returned data is "ok"; otherwise, it will show div#error (again, this is in the html above), delay for 3 seconds, and then hide the message.
The return false; is unnecessary in each instance in your code above because after each conditional, the code ends - there is no other code to prevent from executing (which is why you would use return false; in this context).
You can do the $.trim on the same line as when you assign the variables, like I did with the slideUp, delay, and slideDown.

Related

php not inserting data into table

I have a HTML form
<div class="contact-form col-md-6 " >
<form id="contact-form" method="post" action="" role="form">
<div class="form-group">
<input type="text" placeholder="Your Name" class="form-control" name="name" id="name" required>
</div>
<div class="form-group">
<input type="email" placeholder="Your Email" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<input type="text" placeholder="Your Phone Number" class="form-control" name="phone" id="phone" required>
</div>
<div class="response_msg"></div>
<div id="mail-success" class="success">
Thank you. You are registerd. :)
</div>
<div id="mail-fail" class="error">
Sorry, don't know what happened. Try later :(
</div>
<div id="cf-submit">
<input type="submit" id="contact-submit" class="btn btn-transparent" value="Register" name="submit">
</div>
</form>
</div>
I need to submit form on same page and show message on successfully submission. I am using JS for this
<script>
$(document).ready(function(){
$("#contact-form").on("submit",function(e){
e.preventDefault();
if($("#contact-form [name='name']").val() === '')
{
$("#contact-form [name='name']").css("border","1px solid red");
}
else if ($("#contact-form [name='email']").val() === '')
{
$("#contact-form [name='email']").css("border","1px solid red");
}
else if ($("#contact-form [name='phone']").val() === '')
{
$("#contact-form [name='phone']").css("border","1px solid red");
}
else
{
$("#loading-img").css("display","block");
var sendData = $( this ).serialize();
$.ajax({
type: "POST",
url: "js/ajaxsubmit.php",
data: sendData,
success: function(data){
$("#loading-img").css("display","none");
$(".response_msg").text(data);
$(".response_msg").slideDown().fadeOut(3000);
$("#contact-form").find("input[type=text], input[type=email], textarea").val("");
}
});
}
});
$("#contact-form input").blur(function(){
var checkValue = $(this).val();
if(checkValue != '')
{
$(this).css("border","1px solid #eeeeee");
}
});
});
</script>
As soon i clicked on submit button page refresh but my i don't see my pho code inserting data in database.
<?php
require_once("conn.php");
if((isset($_POST['name'])&& $_POST['name'] !='') && (isset($_POST['email'])&& $_POST['email'] !='') && (isset($_POST['phone'])&& $_POST['phone'] !=''))
{
// require_once("contact_mail.php");
$yourName = $conn->real_escape_string($_POST['name']);
$yourEmail = $conn->real_escape_string($_POST['email']);
$yourPhone = $conn->real_escape_string($_POST['phone']);
$sql="INSERT INTO Beta_Registration (name, email, phone) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."')";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}
else
{
echo "Thank you! We will contact you soon";
}
}
else
{
echo "Please fill Name and Email";
}
?>
I want my form to submit on same page also stays on same block and shows the messages in div inside form when data entered successfully or failed into database.
The issues i am facing whenever i press submit button it refreshed the page and form data doesn't executed into database. It might be php or JS i am using. Please help me in this.
1- You need to add "return false" in your on submit function to prevent browser to submit the form
$(document).ready(function () {
$("#contact-form").on("submit", function (e) {
...
return false;
});
...
});
2- You need to match you database table name, and their columns name which you have used in your MySQL query.

Bootstrap login with javascript

I'm new to Javascript and I need to validate a log-in form with Bootstrap, the thing is not validating the password in the script.
https://jsfiddle.net/98uqsvu2/
<script type="text/javascript">
function check_info()
{
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if(user == "test#gmail.com")
{
if(pass == "123")
{
return true;
}
}
else
{
return false;
}
}
</script>
git: https://gist.github.com/Adaryn/6c38cfafd5e95d8a0bba508a33cebec7
#Adaryn
Since I cannot comment, I posted it as an answer.
I made the following changes to the fiddle and I was able to execute the code.
Removed the link href's from your HTML.
Added the closing body tag.
Moved the script from the javascript code section and pasted it just above the closing body tag.
Here is the updated fiddle.
<div class="container">
<form class="form-signin" form role="form" action="hola.html" name="formlogin" method="post" class="login-form" onsubmit="check_info()">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required="">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<script type="text/javascript">
function check_info()
{
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if(user == "test#gmail.com")
{
if(pass == "123")
{
return true;
}
}
else
{
return false;
}
}
</script>
try this code. also added jsfiddle
document.getElementById("submit-form").addEventListener("click", check_info);
function check_info() {
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if (user == "test#gmail.com" && pass == "123") {
alert("email and password is valid!!!");
return true;
} else {
alert("email and password is NOT valid!!!");
return false;
}
}
https://jsfiddle.net/damaxrss/

Angular validations: Restrict server request if user enters invalid email or password

<form name="LPform" novalidate>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">Email ID</label>
<input class="mob-adj-inpbx " type="email" name="uemail" ng-model="useremail" placeholder=" me#example.com" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.uemail.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.uemail.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.uemail.$dirty && allow_Invalid">
</div>
</div>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">PASSWORD</label>
<input class="mob-adj-inpbx" type="password" name="upassword" ng-model="userpassword" placeholder=" password" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.upassword.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.upassword.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.upassword.$dirty && allow_Invalid">
</div>
</div>
<div id="server_message" class="form-row clearfix basic-error-msg-loginpopup" ng-show="server_message">
{{server_message}}
</div>
<div class="btn-container clearfix mobile-adj" style="margin-left:17.2%;">
<div class="btn-wrap btn-loginpopup">
<input style="max-height:40px;width:121%;" type="submit" name="commit" value="LOGIN" ng-click="login_request()"/>
</div>
</div>
</form>
This part is displayed to the user and the inputs are validated using angular validations. All validations are working fine.
$scope.login_request = function(){
if(LPform.useremail.$valid && LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$http({
method: 'POST',
url: '/users/home_login',
data: {email: $scope.useremail, password: $scope.userpassword}
}).success(function (response) {
console.log(response);
window.location = response.location;
}).error(function (response) {
console.log(response);
$scope.server_message = response.server_message;
});
}
else if(!LPform.useremail.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid email.";
}
else if(!LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid password.";
}
else{
$scope.allow_Invalid = "true";
$scope.server_message = "Request Failed.";
}
};
This part is in javascript file where I want to use the validations to decide whether to send a request to the server or not. The conditions I have used in the if else clause is not working, which I randomly tried btw. I am aware that I can disable Login button, however, I don't want to implement this that way.
I believe your problem is that the form name is bound to $scope and isn't a global variable.
In controller change
LPform
To
$scope.LPform

CAPTCHA fails shows alert but form submitting automatically how to stop this

This is basic registration module in this i added captcha works
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-register" role="form" id="register-form">
<div>
<input name="name" id="name" type="text" class="form-control" placeholder="User name">
<span class="help-block"></span>
</div>
<div>
<input name="email" id="email" type="email" class="form-control" placeholder="Email address" >
<span class="help-block"></span>
</div>
<div>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<span class="help-block"></span>
</div>
<div>
<input name="confirm_password" id="confirm_password" type="password" class="form-control" placeholder="Confirm Password">
<span class="help-block"></span>
</div>
<div>
<td id="imgparent">
<div id="imgdiv">
<img id="img" src="captcha.php">
</div>
<img id="reload" src="images/reload.png">
<input id="captcha1" name="captcha" type="text" class="form-control" placeholder="Enter captcha">
</td>
</tr>
<span class="help-block"></span>
</div>
<button class="btn btn-block bt-login" id="button" type="submit">Sign Up</button>
<h4 class="text-center login-txt-center">Alternatively, you can log in using:</h4>
<a class="btn btn-default facebook_rnd" href="login.php?type=facebook"> <i class="fa fa-facebook modal-icons-rnd"></i> </a>
<a class="btn btn-default google_rnd" href="login.php?type=google"> <i class="fa fa-google-plus modal-icons-rnd"></i> </a>
</form>
it is register.js
$(document).ready(function(){
$("#register-form").validate({
submitHandler : function(e) {
$(form).submit();
},
rules : {
name : {
required : true
},
email : {
required : true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
},
password : {
required : true
},
confirm_password : {
required : true,
equalTo: "#password"
}
},
messages : {
name : {
required : "Please enter name"
},
email : {
required : "Please enter email",
remote : "Email already exists"
},
password : {
required : "Please enter password"
},
confirm_password : {
required : "Please enter confirm password",
equalTo: "Password and confirm password doesn't match"
}
},
errorPlacement : function(error, element) {
$(element).closest('div').find('.help-block').html(error.html());
},
highlight : function(element) {
$(element).closest('div').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('div').removeClass('has-error').addClass('has-success');
$(element).closest('div').find('.help-block').html('');
}
});
});
it is for CAPTCHA js
// JavaScript Document
$(document).ready(function() {
// Change CAPTCHA on each click or on refreshing page.
$("#reload").click(function() {
$("#img").remove();
$('<img id="img" src="captcha.php" />').appendTo("#imgdiv");
});
// Validation Function
$('#button').click(function() {
var name = $("#username1").val();
var email = $("#email1").val();
var captcha = $("#captcha1").val();
if (name == '' || email == '' || captcha == '') {
} else {
// Validating CAPTCHA with user input text.
var dataString = 'captcha=' + captcha;
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
success: function(html) {
if ($.trim(captcha) == '2') {
alert('Entered code is wrong');
reloadCaptcha();
return false;
}
validated = true;
$("#button").submit();
alert(html);
}
});
}
});
});
here when all validation are works fine but if the CAPTCHA is wrong then also it submitting he form why?>>
how to stop when CAPTCHA is worng return to form ??
What you're doing here is never what you want to be doing with Captcha.
The reason Captcha exists is to prevent malicious form submissions, meaning that you're not supposed to be able to submit any data to the server without a valid Captcha. However, what you're doing is validating the Captcha in Javascript, then submitting the form.
There is nothing stopping someone from manually calling $('#button').submit() to push whatever data they like to the server. The Captcha is essentially useless; it's like a door with no walls around it.
You'll need to re-implement your Captcha solution to do the validation on the server side, wherever your form is submitting to. First validate the Captcha, then process the form submission.
You could use something like this:
session_start();
if($_POST['captcha'] != $_SESSION['<insert Captcha Session key here>']) { /* invalid captcha */ }

jQuery Ajax - no success

success in my AJAX call doesn't trigger at all, and I can't figure out why. None of the alerts specified in the AJAX file are popping up.
The form:
<form onsubmit="check_reg();return false;" method="post" name="reg_form" id="reg">
<label class="error" id="reg_error"></label>
<label for="login_reg">Login</label>
<input type="text" name="login" id="login_reg" placeholder="Login">
<label for="email_reg">Email</label>
<input type="text" name="email" id="email_reg" placeholder="Email">
<label for="haslo_reg">Password</label>
<input type="password" name="password" id="pass_reg" placeholder="Password">
<button type="submit">Register</button>
</form>
reg_script.php:
if (!empty($_POST['login']) && !empty($_POST['password']) && !empty($_POST['email'])) {
$login = $mysqli->real_escape_string($_POST['login']);
$password = $mysqli->real_escape_string($_POST['password']);
$email = $mysqli->real_escape_string($_POST['email']);
if ($mysqli->query("INSERT INTO users (login, password, email) VALUES('$login', '$password', '$email')")) {
echo "ok";
}
else {
echo "error";
}
}
else {
echo "empty";
}
AJAX
function check_reg() {
$.ajax({
url: 'reg_script.php',
type: "POST",
data: "login=" + $('#login_reg').val() + "&password=" + $('#pass_reg').val() + "&email=" + $('#email_reg').val(),
success: function(result) {
if (result == 'ok') {
alert('ok');
}
else if (result == 'error') {
alert('error');
}
else if (result == 'empty') {
alert('empty');
}
},
});
}
Any ideas what the problem might be?
EDIT: I should've added that I used this tutorial: http://developertips.net/post/display/web/3/dynamic-login-form-with-ajax-php/ and managed to get the login form working just fine, it's just the registration form that's acting up.
Change
<form onsubmit="check_reg();return false;" method="post" name="reg_form" id="reg">
<label class="error" id="reg_error"></label>
<label for="login_reg">Login</label>
<input type="text" name="login" id="login_reg" placeholder="Login">
<label for="email_reg">Email</label>
<input type="text" name="email" id="email_reg" placeholder="Email">
<label for="haslo_reg">Password</label>
<input type="password" name="password" id="pass_reg" placeholder="Password">
<button type="submit">Register</button>
</form>
to:
<form>
<label class="error" id="reg_error"></label>
<label for="login_reg">Login</label>
<input type="text" name="login" id="login_reg" placeholder="Login">
<label for="email_reg">Email</label>
<input type="text" name="email" id="email_reg" placeholder="Email">
<label for="haslo_reg">Password</label>
<input type="password" name="password" id="pass_reg" placeholder="Password">
<input type="button" onclick="check_reg()">Register</button>
</form>
That way, your HTML file will call your check_reg() which then calls your php-file. You don't need method=post and so on in HTML-file. All this information is already in your function.
Btw, your data-attribute in check_reg() function, I recommend that you change that to serializeArray() instead.
One more thing I just realized:
success: function(result) {
The result-variable contains the error-messages form the serverside (php). so all you have to do is:
success: function(result) {
alert(result);
Here you are using POST request, but sending data as querystring as used for GET request.
Use data in form of object:
data: {'login': $('#login_reg').val() ,'password':$('#pass_reg').val() ,'email':$('#email_reg').val()}
You can also check with print_r($_POST) in your php file, so that you can see, whether data is posted or not.
So use follwing code in ajax:
function check_reg() {
$.ajax({
url: 'reg_script.php',
type: "POST",
data: {'login': $('#login_reg').val() ,'password':$('#pass_reg').val() ,'email':$('#email_reg').val()},
success: function(result) {
if (result == 'ok') {
alert('ok');
}
else if (result == 'error') {
alert('error');
}
else if (result == 'empty') {
alert('empty');
}
},
});
}

Categories