Form submission skip/ignore AJAX function - php

I'm new in php and I want to submit the form to func_login.php by AJAX, instead of using action="func_login.php". So I can handle the error on the same page when user fail to login.
but the AJAX is not working, the form submission skip/ignore the AJAX and direct to func_login php page. I don't know how to check/debug the error in AJAX. What's wrong is my code?
header.php
<form method="post" id="sign-in-form" action="func_login.php" enctype="multipart/form-data">
<div class="form-group">
<label for="mailInput">Email address</label>
<input type="email" class="form-control" id="mailInput2" aria-describedby="emailHelp" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="passInput">Password</label>
<input type="password" class="form-control" id="passInput2" placeholder="Password" name="password">
</div>
<button type="submit" class="border-0 bg-yellow btn-normal col mt-3" name="submit_login">Login</button>
</form>
func_login.php
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$myemail = mysqli_real_escape_string($connection, $_POST['email']);
$mypassword = mysqli_real_escape_string($connection, $_POST['password']);
$sql = "SELECT * FROM users WHERE email = '".$myemail."'";
$result = mysqli_query($connection, $sql);
$count = mysqli_num_rows($result);
if($count == 1) {
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$salt = $row["salt"];
$db_encrypted_password = $row["password"];
if(password_verify($mypassword.$salt,$db_encrypted_password)){
echo "valid";
}else{
echo "invalid";
}
}
}
?>
js.php
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script defer src="https://use.fontawesome.com/releases/v5.5.0/js/all.js" integrity="sha384-GqVMZRt5Gn7tB9D9q7ONtcp4gtHIUEW/yG7h98J7IpE3kpi+srfFyyB/04OV6pG0" crossorigin="anonymous"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.bootstrapvalidator/0.5.0/js/bootstrapValidator.min.js"></script>
<script>
//...Some BootstrapValidotor Code
$('#sign-in-form').on('submit',function(e){
e.preventDefault();
$.ajax({
url: '/func_login.php',
data: {
myemail=$("#mailInput2").val(),
mypassword=$("#passInput2").val();
},
dataType: 'json',
type: 'POST',
success: function(data) {
header("location: welcome.php");
alert("true");
},
error: function(data) {
alert("false");
//HANDLE ERROR HERE (POP OUT SOME ERROR DIALOG AND STAY ON SAME PAGE)
}
});
});
</script>

PHP Header won't work in jquery
try this
$('#sign-in-form').on('submit',function(e){
e.preventDefault();
var redireectUrl = 'welcome.php';
$.ajax({
url: 'func_login.php',
data: {
myemail=$("#mailInput2").val(),
mypassword=$("#passInput2").val();
},
dataType: 'json',
type: 'POST',
success: function(data) {
window.location.href = redireectUrl;
alert("true");
},
error: function(data) {
alert("false");
//HANDLE ERROR HERE (POP OUT SOME ERROR DIALOG AND STAY ON SAME PAGE)
}
});
});

Related

Submit form using Ajax/Jquery and check result?

I am wanting to submit a form using ajax to go to my page 'do_signup_check.php'.
There it will check the email address the user entered against the database to see if there is a match.
If there is a match I want my ajax form to redirect the user to the login.php page.
If there isn't a match I want it to load my page 'do_signup.php'
for some reason the code seems to be doing nothing. Please can someone show me where I am going wrong?
My Ajax form:
<html lang="en">
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
<?php include 'assets/config.php'; ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
</head>
<body>
<div class="sign_up_contain">
<div class="container">
<div class="signup_side">
<h3>Get Onboard.</h3>
<h6>Join the directory.</h6>
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
My Do_Signup_Check.php page:
<?php
session_start();
require 'assets/connect.php';
$myName = $_POST["name"];
$myEmail = $_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn));
}
if (mysqli_num_rows($check) > 0) {
echo '1';
} else {
echo '0';
}
?>
Try to use input id 'submt' to trigger the form as such :
$("#submt").click(function(){
e.preventDefault();
//your logic
You have not included the jquery in your page, the function is also missing the closing parentheses.
Include the jquery at the top
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Replace your function with the following code:-
<script>
$(function () {
$('form').on('submit', function (e) {alert(123);
e.preventDefault();
$.ajax({
type: 'post',
url: 'receive-callback.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('login.php',function(){}).hide().fadeIn(500);
});
}
}
});
});
});
</script>
After receiving success in Ajax and doing all necessary logic (fadeOut etc) just relocate user to login.php:
window.location.href = 'path/to/login.php';
Otherwise, in error function (it is goes just after success function) do the next:
window.location.href = 'path/to/do_signup.php';
Upd:
In case you want to have some piece of code from another file, you can use jQuery method load.
$('#some-selector').load('path/to/course/login.php');
It's a very basic example of using 'load', go google around it to explore more.
Please Try this code.
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function (result) {
if(result == 0){
window.location.href = 'do_signup.php';
}else{
window.location.href = 'login.php';
}
});
My Do_Signup_Check.php page:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn));
}
if(mysqli_num_rows($check) > 0){
echo json_encode(array('result'=>'1'));
exit;
}else{
echo json_encode(array('result'=>'0'));
exit;
}
?>
I hope this will work for you.

cordova app with jquery, php

I'm trying to make a hybrid app using cordova and I want to ask two questions?
One of them is the login, I did it with jquery
<script type="text/javascript">
$(document).ready(function () {
$("#submit_btn").on("click", function(){
var username = $("#username").val();
var pass = $("#pass").val();
$.ajax({
type: "POST",
url: "link",
data: { username: username},
sucess: function () {
}
})
});
});
</script>
Is this a "right" way to do it?
and the best way to connect to a database?
<?php
header('Acess-Controll-Allow-Origin: *');
header('Acess-Controll-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
if(isset($_POST)) {
$username = $_POST['username'];
$pass = $_POST['pass'];
require("connect.php");
$sql = "INSERT INTO fields VALUES ('$username'. '$pass')";
mysqli_query($mysqli, $sql);
}
?>
I'm getting this error:
Notice: Undefined index: $username in /home/wm29tzgj/public_html/areacliente/insert.php on line 7
Notice: Undefined index: $pass in /home/wm29tzgj/public_html/areacliente/insert.php on line 8
<div class="signin-form">
<div class="container">
<form class="form-signin" method="post" id="login-form">
<h2 class="form-signin-heading">Log In to WebApp.</h2><hr />
<div id="error">
<!-- error will be shown here ! -->
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Username" name="username" id="username" />
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" />
</div>
<hr />
<div class="form-group">
<button type="submit" class="btn btn-default" name="btn-login" id="btn-login">
<span class="glyphicon glyphicon-log-in"></span> Sign In
</button>
</div>
</form>
</div>
</div>
Like this :
<script type="text/javascript">
$(document).ready(function () {
$("#submit_btn").on("click", function(){
var username = $("#username").val();
var pass = $("#password").val();
$.ajax({
type: "POST",
url: "http://website.php",
data: {'username': username,"pass":pass },
cache: false,
success: function (data) {
}
});
});
</script>
<script type="text/javascript">
var username="";
var passTxt="";
$(document).ready(function () {
$("#submit_btn").on("click", function(){
username = $("#username").val();
passTxt = $("#password").val();
$.ajax({
type: "POST",
url: "http://website.php",
data: {'username': username,"pass":passTxt },
cache: false,
success: function (data) {
}
});
});
</script>

seems that login-page is reloading after false form-validation

I was changing my loginpage and I've put the jquery with the form-validation in a separate file instead of on the page itself.
$(document).ready(function(){
$("#confirm").on("click", function(e){
e.PreventDefault();
var check = true;
var empty_fields = ['name','password'];
for (i=0; i<empty_fields.length; i++) {
var $field = $('#'+empty_fields[i]);
if ($.trim($field.val()) == '') {
$field.addClass('error');
check = false;
}
else {
$field.removeClass('error');
}
}
if (check == true)
{
$.ajax({
type: 'POST',
url: 'PHPCalls.php?CallID=Login',
data: $("#loginform").serialize(),
success: function(data) {
var result = $.trim(data);
if(result == 'true') {
alert('succeeded');
}
}
});
}
});
});
Before the part where I do my check on the input being empty was on the login-page itself and worked fine. I called it with an onclick="return check_form();" and then returned the value 'check' being true or false.
Since I've put this script in a separate file it seems like the page is reloading itself. When I click on the confirm-button the input-boxes get the error-layout but then the page flashes and all is set back to normal...I have no clue what is happening...
Anyone can set me on the right track?
This is a stripped part of the login-page
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/ajaxLogin.js"></script>
<script type="text/javascript" src="js/sha512.js"></script>
<script type="text/javascript" src="js/forms.js"></script>
</head>
<body>
<form name="loginform" class="loginform" action="#" method="post">
<input type="text" name="name" id="name" class="input username" placeholder="Name" onfocus="this.value=''" />
<input type="password" name="password" id="password" class="input password" placeholder="Wachtwoord" onfocus="this.value=''" />
<input type="submit" id="confirm" value="Login" class="button" />
</form>
</body>
SOLUTION: add PreventDefault() and remove formhash()
You need to return false if check! = true
if (check == true)
{
$.ajax({
type: 'POST',
url: 'PHPCalls.php?CallID=Login',
data: $("#loginform").serialize(),
success: function(data) {
var result = $.trim(data);
if(result == 'true') {
alert('succeeded');
}
}
});
}
else
{
return false;
}
Try this

Form still redirect to PHP with preventDefault

EDIT:
This was related to a typo elsewhere in my Javascript. I had forgotten to check the Javascript console. Thank you for your comments.
This is my first post on this site. I have been reading it for a long while though.
I am working on a login form utilizing jQuery, AJAX, and PHP. Several times now I have run into the problem where I am redirected to the PHP page where I see the echoed data I wanted returned. I have tried to figure this out but I am stuck.
EDIT:
I did include jQuery:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
HTML:
<form name="login" id="loginForm" action="login.php" method="post">
<label for="usernameInput">Username: </label>
<input type="text" name="usernameInput" id="usernameInput" placeholder="Username" autofocus required>
<label for="passwordInput">Password: </label>
<input type="password" name="passwordInput" placeholder="Password" required>
<input type="submit" name="loginSubmit" value="Log In">
</form>
jQuery:
function login () {
$('#loginForm').on('submit', function(e){
e.preventDefault();
var formObject = $(this);
var formURL = formObject.attr("action");
$.ajax({
url: formURL,
type: "POST",
data: formObject.serialize(),
dataType: 'json',
success: function(data)
{
$("#loginDiv").remove();
if(data.new) {
$("#setupDiv").show();
} else {
statusUpdate();
/* EDIT: Changed from dummy text 'continue()' */
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#loginDiv").append(textStatus);
}
});
});
}
Call:
$(document).ready(function() {
login();
});
PHP:
// Main
if (isset($_POST['usernameInput'], $_POST['passwordInput']))
{
require "hero.php";
// Starts SQL connection
$sql = getConnected();
$userArray = validateUser($sql);
if ( $userArray['id'] > 0 ) {
sessionSet($userArray);
$userArray['user'] = (array) unserialize($userArray['user']);
$userArray = json_encode($userArray);
echo $userArray;
exit();
}
else
{
echo 'Username does not exist';
}
}
else
{
echo "Please enter a username and password.";
}
I know I have not included everything, but here's the output:
{"id":"11","name":"st5ph5n","new":true,"user":[false]}
So everything up to $userArray is working as expected. Why is this not staying on index.html and instead redirecting to login.php?
Thank you for any responses.

Ajax/PHP login form - developing an android app(Jquery.mobile) using phonegap

My Index.html file code as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mindcorpus - Placement</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery-mobile.js" type="text/javascript"></script>
<script src="/cordova.js" type="text/javascript"></script>
<script>
$(function()
{
$('#frm').submit(function()
{
var username = $('#textinput').val();
var username = $.trim(username);
var password = $('#passwordinput').val();
var password = $.trim(password);
if(username=='')
{
$('.error').html('Please enter username');
return false;
}
else if(password =='')
{
$('.error').html('Please enter password');
return false;
}
else
{
var user = $('[name=username]').val();
var pass = $('[name=password]').val();
$.ajax({
type: 'POST',
url: 'http://localhost/mc-new/admin/mobile1/process.php',
data: { username: user, password: pass},
success: function(data){
alert(data.success);
},
error: function(){
alert('error!');
}
});
return false;
}
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<div data-role="header">
<h1><img src="images/logo.png" /></h1>
</div>
<div data-role="content">
<div class="error"></div>
<form action="" method="post" id="frm">
<div data-role="fieldcontain">
<input type="text" name="username" placeholder="Username" id="textinput" value="" />
</div>
<div data-role="fieldcontain">
<input type="password" name="password" placeholder="******" id="passwordinput" value="" />
</div>
<button data-icon="arrow-r" type="submit">Submit</button>
</form>
</div>
<div data-role="footer">
<h4 style="font-weight:normal">Powered By: Mind Processors</h4>
</div>
</div>
</body>
</html>
And my process.php file is:
<?php
if(isset($_POST['username']) || isset($_POST['password']))
{
$data['success'] = 'Done';
echo json_encode($data);
}
?>
This functions is properly working when I use localhost on my browser. BUt when I use Dreamweaver and build & Emulate this site. It always alert error. The Ajax is not functioning in emulator. The request is not passed to process file. Please help me & sort out this problem.
You need to specify in the ajax that the expected return data type is JSON and also cross domain has to be enabled.
Try the below code for the ajax,
$.ajax({
type: 'POST',
url: 'http://localhost/mc-new/admin/mobile1/process.php',
crossDomain: true,
data: { username: user, password: pass},
dataType: 'json',
success: function(data){
alert(data.success);
},
error: function(){
alert('error!');
}
And also add the following in your php file,
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');
header('Content-Type: application/json');
if(isset($_POST['username']) || isset($_POST['password']))
{
$data['success'] = 'Done';
echo json_encode($data);
}
?>
Hope this helps to someone who falls onto this question, looking for an answer.

Categories