I try this php code(I have already read about sql Injection)but apparently it does not run, no error message or anything else ...
<?php
function SignIn(){
session_start();
require_once("dbConnection.php");
if(isset($_POST['submit'])){
$db_handle = new DBConnection();
$username = $_POST["username"];
if(filter_var($username, FILTER_VALIDATE_EMAIL)===true && strpos(explode('#',$username),"studio.unibo.it")===true){
$query = $db_con->prepare("SELECT * FROM studenti_in_sessione
WHERE Username=:username");
$query->execute(array(":username"=>$username));
$row = $query->fetch(PDO::FETCH_ASSOC);
$count = $query->rowCount();
if($row['Username']==$username){
echo "<script language = javascript>
alert(\"Autenticazione riuscita,Le invieremo nella mail istituzionale un codice univoco di autenticazione.\");
window.history.go(-1);
</script>";
$querySession = $db_con->prepare("SELECT Nome, Cognome, Matricola FROM studenti_in_sessione
WHERE Username:=username");
$querySession->execute(array(":username"=>$username));
$rowStud = $querySession->fetch(PDO::FETCH_ASSOC);
$exit = array_values($rowStud);
$queryInsert = $db_con->prepare("INSERT INTO studente (Nome, Cognome, Matricola, Username, Codice) VALUES('".$exit[0]."',
'".$exit[1]."','".$exit[2]."','".$username."');");
$resultInsert = $queryInsert->execute();
sendCode($username);
}
}}else{
echo "<script language = javascript>
alert(\"L'indirizzo deve essere #studio.unibo.it.\");
window.history.go(-1);
</script>";
}
if(isset($_POST['submit'])){
SignIn();
}
?>
This is html form
<div class="box-header">
<h2>Login</h2>
</div>
<form name="form" class="form" method="POST">
<label for="username">Username</label>
<br/>
<input type="text" id="username" name="username">
<input name="submit" id="submit" type="submit" value="Login">
</div>
Finally script.js
$('document').ready(function()
{
/* validation */
$(".form").validate({
rules:
{
user_email: {
required: true,
email: true
},
},
messages:
{
user_email: "please enter your email address",
},
submitHandler: submitForm
});
/* validation */
/* login submit */
function submitForm()
{
var data = $(".form").serialize();
$.ajax({
type : 'POST',
url : '../Slide_upload/database/signIn.php',
data : data,
success : function(response){
if(response=="ok"){
}
else{
}
}
});
return false;
}
/* login submit */
});
I probably made mistakes but I can not figure out where ...
For sure, you are missing a bracket to close your function that is not being executed.
Add it before the lines
if(isset($_POST['submit'])){
SignIn();
}
This will make your function call working.
Related
I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.
I have a sample script that will authenticate my users to access the page. My issue is when I post the values the js file does reflect that the data has been serialized but when it is posted to the php file to check if the database record exists the users still gets access to the page whether the login in details are correct or wrong. For some reason it seems not to take my `$_POST['pass'] and my $_POST['user_email'] values. But if I manually type in the user email and password in the php file to replace the variables it will works.
HTML form
<form class="login" id="login-form" name="login-form" method="post">
<p class="title">LOGIN</p>
<input type="text" placeholder="Email" id="user_email" name="user_email" autofocus/>
<i class="fa fa-user"></i>
<input type="password" placeholder="Password" id="pass" name="pass" />
<i class="fa fa-key"></i>
<button>
<i class="spinner" style="outline:none;"></i>
<span class="state">Log in</span>
</button>
</form>
My js file to post the values. I added the console.log just to test see what values are been taken in by the script
$('document').ready(function()
{
var working = false;
$('.login').on('submit', function(e) {
e.preventDefault();
if(working)return
working = true;
var $this = $(this),
$state = $this.find('button > .state');
$this.addClass('loading');
$state.html('Authenticating');
var data = $("#login-form").serialize();
console.log(data);
$.ajax({
type : 'POST',
url : 'login_process.php',
data : data,
success : function(response) {
console.log(response);
if(response=="ok"){
setTimeout(function() {
$this.addClass('ok');
$state.html('Welcome');
setTimeout(function() {
$state.html('Log in');
$this.removeClass('ok loading');
working = false;
}, 4000);
setTimeout(function() {
window.location.href = "/Home.aspx";
}, 4000);
}, 3000);
//$("#btn-login").html('<img src="btn-ajax-loader.gif" /> Signing In ...');
//setTimeout(' window.location.href = "home.php"; ',4000);
} else {
console.log('ERROR IN LOGINING IN');
}
}
});
return false;
});
});
PHP file 'login_process'
<?php
session_start();
require_once 'dbconfig.php';
if(isset($_POST['pass']))
{
$user_email = urldecode(trim($_POST['user_email']));
$user_password =trim($_POST['pass']);
//$password = md5($user_password);
$password = $user_password;
try {
$stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_email=:email");
$stmt->execute(array(":email"=>$user_email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if($row['user_password']==$password){
echo "ok"; // log in
$_SESSION['user_session'] = $row['user_id'];
}
else{
echo "email or password does not exist."; // wrong details
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
You are missing the dataType make with dataType : 'json' just after data, You can return the result in json by json_encode() ti debug result
Im all new to ajax and jquery so iam asking u guys for some help. I have to forms that one creates a new user and second logs the user in.
The functions work greate, but i want to create alert boxes for success or failure of the functions.
And i dont know how... Here is my code
HTML
<!-- Formular for signing up -->
<h4 class="form-headline"> Not a member? Sign up here </h4>
<form method="post">
<div class="form-group">
<label> Username </label>
<input type="text" class="form-control" id="newusername">
</div>
<div class="form-group">
<label> Password </label>
<input type="password" class="form-control" id="newpassword">
</div>
<div class="form-group">
<label> Your club </label>
<input type="text" class="form-control" id="newclub">
</div>
<input type="button" id="btn-reg" class="btn btn-success" value="Sign up!">
</form>
Script
// -----------------Registration of new user----------------------
console.log('Script loaded...');
// Calling for the method - reg
$("#btn-reg").on("click", reg);
function reg(e) {
e.preventDefault();
console.log('Klick, klick...');
// Declaring variables
var newusername=$("#newusername").val();
var newpassword=$("#newpassword").val();
var newclub=$("#newclub").val();
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},
function(data){
console.log(data);
});
}
PHP
// Creating instance of the class userClass.php
var_dump($_POST);
if(isset($_POST['newusername'])){
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newclub = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user = new User();
$user->newUsers($newusername, $hashpassword, $newclub);
} else {
}?>
OOP
// >>>>>>>>>>>>>>>> Function for saving new user to database
public function newUsers($newusername, $hashpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username, password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $hashpassword, $newclub);
if($stmt->execute()) {
echo "<h3 class='usercreated'>Created</h3>";
} else {
echo "<h3 class='usercreated'> Failed </h3>";
}
}
Just noticed that you are using function to create a new user, my bad again
if(isset($_POST['newusername'])){
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newclub = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user = new User();
$status = $user->newUsers($newusername, $hashpassword, $newclub);
if($status) {
echo json_encode(array("status" : "success"));
}else {
echo json_encode(array("status" : "failed"));
}
}
Make a return from this function
public function newUsers($newusername, $hashpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username, password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $hashpassword, $newclub);
if($stmt->execute()) {
return true;
}else {
return false
}
}
this will be the same
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},
function(data){
var object = JSON.parse(data);
alert(object.status);
// or you can add if else by using the status
});
}
You could just echo the script tag.
if($stmt->execute()) {
echo "<h3 class='usercreated'>Created</h3>";
echo "<script type="text/javascript">";
echo "alert("Hello World!")";
echo "</script>";
} else {
echo "<h3 class='usercreated'> Failed </h3>";
echo "<script type="text/javascript">";
echo "alert("Hello World!")";
echo "</script>";
}
}
For the Script block.
var posting = $.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
});
posting.done(function( data ) {
alert( "Data Loaded Ok");
});
posting.fail(function( data ) {
alert( "Error loading data");
});
Hope this helps you.
I have a simple login form in which I have passed the values through AJAX call. The problem is when I enter wrong email or password for first time, It displays me the error message. 2nd time if I enter something wrong it does not show the error. Where am I doing wrong any suggestions/help please.
Form
<?php
if (isset($_SESSION['login_email']) && !empty($_SESSION['login_email'])) {
//header('Location:profile.php');
?>
<script> location.replace("profile.php"); </script>
<?php
} else {
?>
<div class="login_form">
<h1 class="login_heading">Login</h1>
<div class="alert-error"></div>
<div class="alert-success"></div>
<div class="login">
<form method="post" action="">
<label >Email</label>
<input class="inputs_login" type="email" name="email" id="email" placeholder="email" >
<label>Password</label>
<input class="inputs_login" type="password" name="password" id="password" placeholder="password"><br>
<input type="button" name="login_submit" id="login_submit" value="login">
</form>
</div>
</div>
<?php
}
?>
Ajax
<script>
$(document).ready(function() {
$('#login_submit').click(function(e){
//e.preventDefault();
var email = $("#email").val(),
password = $("#password").val();
var proceed = true;
if(proceed){
post_data= { 'Email': email, 'Password': password};
$.post('login_index.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output=$('.alert-error').html(response.text);
}else{
location.href="profile.php";
}
$(".alert-error").delay(3200).fadeOut(300);
}, 'json');
}
});
});
</script>
php
<?php
include "db/db.php";
session_start();
if ($_POST) {
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(array(
'type' => 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if (isset($_POST['Email']) && isset($_POST['Password'])) {
$email = filter_var($_POST["Email"], FILTER_SANITIZE_STRING);
$pwd = filter_var($_POST["Password"], FILTER_SANITIZE_STRING);
$query = mysqli_query($con, "select * from customers where email='$email' and password='$pwd'");
$count = mysqli_num_rows($query);
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
if ($row) {
$_SESSION['login_email'] = $row['email'];
$output = json_encode(array(
'type' => 'message',
'text' => 'Hi ' . $email . ' You are successfully login'
));
die($output);
} else {
$output = json_encode(array(
'type' => 'error',
'text' => 'Could not Login! Please check your email/password OR REGISTER FREE ACCOUNT .'
));
die($output);
}
}
}
?>
I am using jquery to make a .php file execute but my major problem is when ever a error is thrown from back-end i used a alert to display that error_msg..but ever i submit with a error intentionally...its just moving on to page specified in action...no error alert poped up...plz help me out of this.!!pardon me if am wrong
here gose the DB_Function.php
<?php
class DB_Functions {
private $db;
// constructor for database connection
function __construct() {
try {
$hostname = "localhost";
$dbname = "miisky";
$dbuser = "root";
$dbpass = "";
$this->db = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e)
{
die('Error in database requirments:' . $e->getMessage());
}
}
/**
* Storing new user
* returns user details of user
*/
public function storeUser($fname, $lname, $email, $password, $mobile) {
try {
$hash = md5($password);
$sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
return false;
}
/*to check if user is
already registered*/
public function isUserExisted($email) {
try{
$sql = "SELECT email FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
}
/*to check if user
exist's by mobile number*/
public function isMobileNumberExisted($mobile){
try{
$sql = "SELECT mobile FROM users WHERE mobile = '$mobile' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch(Exception $e){
die('Error accessing database: ' . $e->getMessage());
}
}
//DB_Functions.php under construction
//more functions to be added
}
?>
here gose the .php file to be clear on what am doing..!!
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
// receiving the post params
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$mobile = trim($_POST['mobile']);
// validate your email address
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate your password
if(strlen($password) > 6){
//validate your mobile
if(strlen($mobile) == 12){
//Check for valid email address
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
if($db->isMobileNumberExisted($mobile)) {
//user already existed
$response["error"] = true;
$response["error_msg"] = "user already existed with" . $mobile;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
}
} else {
$response["error"] = true;
$response["error_msg"] = "Mobile number is invalid!";
echo json_encode($response);
}
} else {
//min of 6-charecters
$response["error"] = true;
$response["error_msg"] = "password must be of atleast 6-characters!";
echo json_encode($response);
}
} else {
// invalid email address
$response["error"] = true;
$response["error_msg"] = "invalid email address";
echo json_encode($response);
}
} else {
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
and here gose the main file .js
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
e.preventDefault();
}
});
});
});
and here gose the corresponding .html file
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required="">
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required="">
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required="">
</div>
<div class="form-group" id="recaptcha_widget">
<div class="required">
<div class="g-recaptcha" data-sitekey="6Lc4vP4SAAAAABjh8AG"></div>
<!-- End Thumbnail-->
</div>
<?php include("js/captcha.php");?>
</div>
<div class="form-group">
<div cle the terms and policy </label></div>
</div>ass="checkbox i-checks"><label> <input type="checkbox"><i></i> Agre
<button type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b">Register</button>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
<
/form>
From the comments:
So only after displaying Registeration successful! I want to submit the form and redirect it to login.html
Well the solution is quite simple and involved adding and setting async parameter to false in .ajax(). Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.
Your jQuery should be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
So the form will only get submitted if the registration is successful, otherwise not.
Edited:
First of all make sure that <!DOCTYPE html> is there on the top of your page, it stands for html5 and html5 supports required attribute.
Now comes to your front-end validation thing. The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method.
For the purpose of simplicity I removed your terms and conditions checkbox and Google ReCaptcha. You can incorporate those later in your code.
So here's your HTML code snippet:
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required />
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required />
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required />
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required />
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required />
</div>
<!--Your checkbox goes here-->
<!--Your Google ReCaptcha-->
<input type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b" value="Register" />
</form>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
And your jQuery would be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
var status = $('form')[0].checkValidity();
if(status){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
$('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});
your form submit takes action before ajax action so its reloading the page and use form submit instead of submit button click
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
Ok steps to be sure that everthing works fine while you try to use ajax
1st : use form submit and use e.preventDefault(); to prevent page reloading
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
alert('Form submited');
});
if the alert popup and form not reloading the page then the next step using ajax
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
$.ajax({
url: "register.php",
type: "POST",
dataType: "JSON",
data: {success : 'success'},
success : function(data){
alert(data);
}
});
});
and in php (register.php)
<?php
echo $_POST['success'];
?>
this code should alert with "success" alert box .. if this step is good so now your ajax and php file is connected successfully then pass variables and do another stuff