Simple Ajax in PHP login form not working - javascript

I have created a PHP login form where I want to add ajax code in which it helps me to successfully login without loading windows bit during the ajax code are adding .This code is not working. Please help me fix this issue and it is possible that I dont want to show login after page in Jquery . What I mean is that after the login page i dont want dashboard.php to show the user. But my main issue is that my code is not working.Please help and fix my issue.
Thanks in advance.
$.ajax({
method: "POST",
url: "loginpage.php",
dataType: "json",
data: { email: email, password: pass},
success:function(data)
{
if(data.type=='success')
window.location = 'welcomepage_hideme.php';
else
//server side error from php but now
alert("Incorrect email or and password");
}
});
<?php
$msg = "";
if (isset($_POST['submit'])) {
$con = new mysqli('localhost', 'research_emailC', 'test123', 'research_phpEmailConfirmation');
$email = $con->real_escape_string($_POST['email']);
$password = $con->real_escape_string($_POST['pass']);
if ($email == "" || $password == "")
$msg = "Please check your inputs!";
else {
$sql = $con->query("SELECT id, password, isEmailConfirmed FROM users WHERE email='$email'");
if ($sql->num_rows > 0) {
$data = $sql->fetch_array();
if (password_verify($password, $data['password'])) {
if ($data['isEmailConfirmed'] == 0)
$msg = "Please verify your email!";
else {
$msg = "You have been logged in";
header("location: welcomepage_hideme.php");
}
} else
$msg = "Please check your inputs!";
} else {
$msg = "Please check your inputs!";
}
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Log In</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<img src="images/logo.png"><br><br>
<?php if ($msg != "") echo $msg . "<br><br>" ?>
<form method="post" action="loginpage.php">
<input class="form-control" name="email" type="email" placeholder="Email..."><br>
<input class="form-control" name="password" type="password" placeholder="Password..."><br>
<input class="btn btn-primary" type="submit" name="submit" value="Log In">
</form>
</div>
</div>
</div>
</body>
</html>

The problem in the name of getting parameter from $_POST array:
$password = $con->real_escape_string($_POST['pass']);
should be:
$password = $con->real_escape_string($_POST['password']);
Because, in the form it has password name:
<input class="form-control" name="password" type="password" placeholder="Password..."><br>

Please try this.
Ajax code
$(document).ready(function(){
$("#login").submit(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "login.php",
dataType: "json",
data: $(this).serialize(),
success:function(data){
console.log(data);
if(data.type=='success')
window.location = 'welcomepage_hideme.php';
else
//server side error from php but now
alert("Incorrect email or and password");
}
});
});
})
Html code
<div class="container" style="margin-top: 100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<form method="post" name="login_form" id="login_form">
<input class="form-control" name="email" type="email" placeholder="Email..."><br>
<input class="form-control" name="password" type="password" placeholder="Password..."><br>
<input class="btn btn-primary" type="submit" name="submit" value="Log In">
</form>
</div>
</div>
</div>

The hole logic here is incorrect.
First you should move php code out from loginpage.php into fetchLogin.php:
<?php
$result = [ 'status' => false, 'msg' => "Please check your inputs!" ];
if ( isset( $_POST['email'] ) && isset( $_POST['password'] ) ) {
$con = new mysqli( 'localhost', 'research_emailC', 'test123', 'research_phpEmailConfirmation' );
$email = $con->real_escape_string( $_POST['email'] );
$password = $con->real_escape_string( $_POST['pass'] );
if ( $email !== "" && $password !== "" ) {
$sql = $con->query( "SELECT id, password, isEmailConfirmed FROM users WHERE email='$email'" );
if ( $sql->num_rows > 0 ) {
$data = $sql->fetch_array();
if ( password_verify( $password, $data['password'] ) ) {
if ( $data['isEmailConfirmed'] == 0 ) {
$result['msg'] = "Please verify your email!";
} else {
$result['status'] = true;
$result['msg'] = "You have been logged in";
}
}
}
}
}
echo json_encode( $result );
die();
Then update your js:
$.ajax({
method: "POST",
url: "fetchLogin.php",
dataType: "json",
data: { email: email, password: pass}
}).done( function( response ) {
// code for render response.msg
if ( ! response.status ) {
return false;
} else {
setTimeout( window.location = "welcomepage_hideme.php", 3000 );
}
});

Related

How to return JSON in HTML using PHP and AJAX without redirecting?

I have searched a lot for a solution to this problem but I have not found one for it. I am trying to include a form for sending e-mails (a contact us form) on my site (using Bootstrap). PHP is being used for the mailer model.
The problem lies in the message that should appear to the user when the message is sent, the message does not appear in the place assigned to it(#status), but rather I am directed to a new page with array data.https://drive.google.com/file/d/1tH8cVCWpx7pDe2OyxkGSKY6rnqV9KxlL/view?usp=sharing
Note that the message appears in all verification cases (when name or email or subject or message fields is empty), only when the email is sent, it directs me to another page!https://drive.google.com/file/d/1lK11R2a18S2arExDegcZyOnITwRlIOYh/view?usp=sharing
Here is my code:
< script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" > < /script> <
script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" > < /script> <
script >
function validateForm() {
document.getElementById('status').innerHTML = "Sending...";
formData = {
'name': $('input[name=name]').val(),
'email': $('input[name=email]').val(),
'subject': $('input[name=subject]').val(),
'message': $('textarea[name=message]').val()
};
$.ajax({
url: "mail.php",
type: "POST",
data: formData,
dataType: "json",
success: function(data, textStatus, jqXHR) {
$('#status').text(data.message1);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], textarea").val("");
},
error: function(jqXHR, textStatus, errorThrown) {
$('#status').text(jqXHR);
}
});
} <
/script>
<div class="col-lg-8">
<form id="contact-form" name="contact-form" action="mail.php" method="POST">
<div class="row ">
<div class="form-group col-md-6">
<input class="form-control" placeholder="Name" id="name" name="name" required="required">
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" placeholder="Email" id="email" name="email" required="required">
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control" placeholder="Subject" id="subject" name="subject" required="required">
</div>
<div class="form-group col-md-12">
<textarea type="text" class="form-control" rows="6" placeholder="Message" id="message" name="message" required="required"></textarea>
</div>
</div>
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-lg btn-primary ml-auto" onclick="validateForm();">Send Message</button>
</div>
<div class="status" id="status"></div>
</form>
</div>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
header('Content-Type: application/json');
$data = array();
if ($name === ''){
$data['message1'] = 'Name cannot be empty.';
$data['code'] = 0;
print json_encode($data);
exit();
}
if ($email === ''){
$data['message1'] = 'Email cannot be empty.';
$data['code'] = 0;
print json_encode($data);
exit();
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$data['message1'] = 'Email format invalid.';
$data['code'] = 0;
print json_encode($data);
exit();
}
}
if ($subject === ''){
$data['message1'] = 'Subject cannot be empty.';
$data['code'] = 0;
print json_encode($data);
exit();
}
if ($message === ''){
$data['message1'] = 'Message cannot be empty.';
$data['code'] = 0;
print json_encode($data);
exit();
}
$content="From: $name \nEmail: $email \nMessage: $message";
$recipient = "******#gmail.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
$data['message1'] = 'Email successfully sent!';
$data['code'] = 1;
print json_encode($data);
exit();
?>
The problem you experience is that upon the form's submission's default behavior is the behavior you usually see when browsers are interacting with the HTTP protocol. Your button is of type submit and it submits the form.
Assuming that you handle all the logic that you want inside validateForm, the thing your code is missing is that your intention is to prevent the default behavior on submit:
$("#contact-form").submit(function(e) {
e.preventDefault();
});

JQuery Mobile - Registration Form - The JS cannot call the php

I have created a registration form, but the js file cannot call the php.
Are there anyone can give me some advise?
My question is when I click the submit button, there is no reaction. Do I have any mistakes? Thanks
<!DOCTYPE html>
<html>
<head>
<meta name="robots" content="noindex, nofollow">
<title>Tittle</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script type="text/javascript" src="js/registration.js"></script>
<link href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css"
rel="stylesheet" type="text/css"/>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"
type="text/javascript"></script>
<script src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"
type="text/javascript"></script>
<script type="text/javascript" src="js/registration1.js"></script>
<script type="text/javascript">
$(document).on("mobileinit", function() {
$.extend( $.mobile , {
pageLoadErrorMessage: 'Either the page cannot be found or it cannot
be loaded.'
});
});
$(document).on("pageinit","#page", function() {
alert("pageinit is bound!");
});
</script>
</head>
<body>
<div class="container">
<div class="main">
<div data-role="header">
<h1>Register</h1>
</div>
<form class="form" method="post" action="#">
<label>Name :</label>
<input type="text" name="dname" id="name">
<label>Email :</label>
<input type="text" name="demail" id="email">
<label>Password :</label>
<input type="password" name="password" id="password">
<label>Confirm Password :</label>
<input type="password" name="cpassword" id="cpassword">
<button type="button" name="register" id="register"
class="btn">Submit</button>
</form>
</div>
</div>
<div data-role="footer">
<h4>Footer</h4>
</div>
</body>
</html>
Below is the JS
$(document).ready(function () {
$("#register").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should atleast 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function (data) {
if (data == 'You have Successfully Registered.....') {
$("form")[0].reset();
}
alert(data);
});
}
});
});
Below is the PHP
$hostname = "127.0.0.1";
$username = "root";
$password = "123456";
$connection = mysql_connect($hostname, $username, $password) or die("Could
not open connection to database");
$db = mysql_select_db("mydb", $connection); // Selecting Database.
$name=$_POST['name1'];
$email=$_POST['email1'];
$password= sha1($_POST['password1']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "Invalid Email.......";
}
else{
$result = mysql_query("SELECT * FROM registration WHERE email='$email'");
$data = mysql_num_rows($result);
if(($data)==0){
$query = mysql_query("insert into registration(name, email, password) values
('$name', '$email', '$password')"); // Insert query
if($query){
echo "Successfully Registered";
}
else
{
echo "Error";
}
}
else{
echo "This email is already registered. Please try again";
}
}
mysql_close ($connection);
?>
Your form action is empty try changing action="#" to action="register.php"

web page accessible by user authorized/unauthorized and causes error

My page is main.php it was made like this code
<?php
include_once('createtables.php');
include('function.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../includes/css/bootstrap.min.css">
<link rel="stylesheet" href="../includes/css/main.css">
<script src="../includes/js/jQuery.js"></script>
<script src="../includes/js/login.js"></script>
<script src="../includes/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<form id="lgform" action="checklogin.php" method="post">
<h4 class="text-primary" id="llc"><img src="../includes/img/chatballoon.png"> Network Chat </h4>
<div class="input-group" id="firstone">
<span class="input-group-addon">
<span class="glyphicon glyphicon-user"></span>
</span>
<input type="text" class="form-control" placeholder="Enter Account name" id="username" name="username" autofocus>
</div>
<div class="input-group" id="secondtwo">
<span class="input-group-addon" id="password-addon">
<span class="glyphicon glyphicon-lock"></span>
</span>
<input type="password" class="form-control" placeholder="Enter your password" aria-decribedby="password-addon" id="password" name="password" autofocus>
</div>
Create Account
<input type="submit" class="pull-right btn btn-primary btn-sm" name="submit" id="submit" value="Enter now">
</form>
</div>
</body>
</html>
This is my checklogin php was like this:
<?php
ob_start();
session_start();
include("function.php");
$conn = new Functions();
$conn = $conn->db;
//define username and password
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripcslashes($password);
$salt = "dctech2015ABcRXd";
$password = md5($password) . $salt;
$password = sha1($password);
//SELECT QUERY TO FIND IF INPUT INFORMATION WAS ON DATABASE
$stmt = $conn->query("SELECT * FROM users WHERE username ='$username' AND password='$password'");
//LOOP ENTIRE DATABASE ROW
$count = $stmt->rowCount();
//IF INFORMATION FOUND SELECT STATUS IF ALREADY ONLINE OR NOT
if($count == 1){
$status;
$stmt = $conn->prepare("SELECT status FROM users WHERE username='$username'");
$stmt->execute();
while($checkstatus = $stmt->fetch(PDO::FETCH_OBJ)){
$status = $checkstatus->status;
}
if($status == 'Online'){
echo "online";
}else{
echo "success";
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$stmt = $conn->prepare("UPDATE users SET status='Online' WHERE username='$username'");
$stmt->execute();
}
}
ob_end_flush();
?>
ajax here:
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if(username==""){
alert("Please enter your account name");
}else if(password == ""){
alert("Please enter your password");
}else{
$.ajax({
type: "POST",
url: "checklogin.php",
data: "username="+username+"&password="+password,
success: function(data){
if(data == "success"){
window.location.href="chat.php";
}
else if(data == "online"){
alert("account is already online");
}else{
alert("Invalid Account name/Account password");
}
},error:function(data){
alert("an error occured through data");
}
});
}
document.getElementById("username").value = "";
document.getElementById("password").value = "";
});
return false;
});
problem that checklogin.php file is accessible to browser. what i want is to avoid unauthorized users to go to this page cause even login users if they type on browser register.php it will go to it and says username error etc.
This type of error:
You should respond with the standard http status code: 401, so the browser knows it has failed to load the page:
if($count == 1){
...
} else {
header("HTTP/1.1 401 Unauthorized");
// or for php 5.4:
http_response_code(401);
}
Update:
For the errors you added later:
Before you access the values in $_POST, check if they are present:
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// ... all the rest of your code that depends on $_POST comes here
}
You can add some checking to your check_login script to see if the URL matches and kick it back. if(strpos($_SERVER['REQUEST_URI'], 'register.php')) exit() or something to that affect.

issue with ajax login script

I'm very new to ajax, and I'm trying to make a login script that doesn't require a page reload - it's working well except I attempt to set a session variable on the processing page, but no session variable is set.
My form:
<div class="form-bottom">
<form role="form" class="login-form">
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" name="username" placeholder="Username..." class="form-username form-control" id="username">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" placeholder="Password..." class="form-password form-control" id="password">
</div>
<input type="submit" id="submit" class="btn" style="width:100%;background-color:lightblue;" value="Log In" id="login"/>
</form>
<? echo $_SESSION['Name']; ?>
</div>
My ajax:
<script type="text/javascript" >
$(function() {
$("#submit").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+ username + '&password=' + password;
if(username=='' || password=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "ajax/login.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
window.setTimeout(function () {
location.href = "index.php";
}, 3000);
}
});
}
return false;
});
});
</script>
My php script:
include('./static/config.php');
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_POST)) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($con, $sql);
$exists = mysqli_num_rows($result);
if($exists == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['Name'] = $row['Name'];
}
}
I was able to get it working the way I wanted it to.
Form:
<div id="box">
<div class="row">
<div class="col-sm-6 col-sm-offset-3 form-box">
<div class="form-top">
<div class="form-top-left">
<h3>Log-in</h3>
<span id="error" class="error"></span>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
</div>
<div id="box" class="form-bottom">
<form class="login-form" action="" method="post">
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" name="username" placeholder="Username..." class="form-username form-control" id="username">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" placeholder="Password..." class="form-password form-control" id="password">
</div>
<input type="submit" id="login" class="btn" style="width:100%;background-color:lightblue;" value="Log In" id="login"/>
</form>
</div>
</div>
</div>
</div>
AJAX Code:
<script src="js/jquery.min.js"></script>
<script src="js/jquery.ui.shake.js"></script>
<script>
$(document).ready(function() {
$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "ajax/login.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#login").val('Connecting...');},
success: function(data){
if(data)
{
window.setTimeout(function () {
location.href = "index.php";
}, 3000);
}
else
{
$('#box').shake();
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
</script>
PHP (ajax/login.php):
<?php
include("../static/config.php");
session_start();
if(isSet($_POST['username']) && isSet($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($con,$_POST['username']);
$password=mysqli_real_escape_string($con,$_POST['password']);
$result=mysqli_query($con,"SELECT Name FROM techs WHERE Username='$username' and Password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION['Name']=$row['Name'];
echo $row['Name'];
}
}
?>
Since you've stated you're very new to Ajax, you start off pretty well.
There are however a couple of things to know how this works.
You want to avoid a page refresh, yet you don't print out any responses because you're not returning anything in the ajax request. You instead set a session variable which will show up at the next page request (so a refresh)
$.ajax({
type: 'POST',
url: 'ajax/login.php',
data: { username: $("#username").val(), password: $("#password").val() },
success: function (data) {
$('.form-bottom').html(data); // here we replace the form with output of the ajax/login.php response.
}
});
And for the PHP side of things:
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
if(($result = mysqli_query($con, $sql)) != false){ // always verify if your query ran successfully.
if(mysqli_num_rows($result)){ // or compare with == 1, but assuming a username is unique it can only be 1 so it equals to true.
echo mysqli_fetch_assoc($result)['name']; // index, columns, etc should always be lower cased to avoid confusion.
// Obviously you can store it in a session
// But for now just output the data so we can use it as our response.
// json is very usefull with sending large amounts of data.
}
}
The idea of Ajax is that you can request an update, but you need to update your page with javascript manually in order to make it work.
I think you forget to start the session.So start the session at the top of your script. Hope it will help.
session_start();
include('./static/config.php');
if(isset($_POST)) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($con, $sql);
$exists = mysqli_num_rows($result);
if($exists == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['Name'] = $row['Name'];
}
}
3 things you could try:
On the page where you are trying to set the session variable you would have to use proper php opening tags like <?php
Second thing is that you would have to put a value in your session like $_SESSION['hello'] = 'hello';
Third thing, on every page where you handle your session you would have to call <?php session_start(); ?> for it to work.
Goodluck!

ajax form post succes messages

I want to have an account signup page where I check if the is email already used. If so the PHP should send a message saying so, else there should be an insert statement. What I have now is an html form which gets submitted via javascript to php, this all works, but i cant't get any error messages to work. How can i use an server (PHP) response in my javascript?
Server:
<?php
require 'config.php';
require 'resources/password.php';
$con = mysqli_connect($url,$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$verifyemail = mysqli_real_escape_string($_POST['email']);
$numberofrowsquery = "select * from `users` where `user_email`='$email'";
$numberofrows=mysqli_query($con,"select * from `users` where `user_email`='$email'");
//$exitst = mysqli_num_rows($numberofrows);
if($numberofrows->num_rows)
{
//echo "exist";
echo json_encode(array(
'status' => 'exist',
'message'=> 'exist message'
));
}
else
{
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 10));
$query = "INSERT INTO users(user_email, username, user_voornaam,user_achternaam,user_password,user_hash) VALUES ('$email', '$username', '$name','$lastname','$password','$hash')";
$succes = mysqli_query($con,$query);
if($succes){
//echo "success";
echo json_encode(array(
'status' => 'success',
'message'=> 'success message'
));
}
else{
//echo"failed";
echo json_encode(array(
'status' => 'failed',
'message'=> 'failed message'
));
}
}
mysqli_close($con);
//echo "Uw account is succesvol geregistreerd.";
?>
HTML / Javascript:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ajax example</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div id="message"></div>
<form id="myform" action="http://stopfoodwaste.stefspakman.com/app/signup.php">
<input type="text" name="name" required/>
<input type="text" name="lastname" required/>
<input type="text" name="username" required/>
<input type="text" name="email" required/>
<input type="password" name="password" required/>
<input type="submit" value="submit"/>
</form>
<div id="response"></div>
<script>
$(function() {
$("#myform").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
beforeSend: function() {
$("#message").html("sending...");
},
success: function(data) {
if(data.status === "success"){
$("#message").hide();
$("#response").html(data);
alert("succes");
location.reload();
}
else if(data.status === "exist"){
$("#message").hide();
alert("Dit emailadress is reeds in gebruik, probeer in te loggen of gebruik een ander mailadres.");
}
else if(data.status === "failed"){
alert("Something Went wrong");
}
}
});
});
});
</script>
</body>
</html>
Anyone some suggestions?
Replace your submit button with simple button and form submit event to button click event. Since you used the submit button, it always submits to action php file.
Update you HTML code like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ajax example</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div id="message"></div>
<form id="myform" action="http://stopfoodwaste.stefspakman.com/app/signup.php">
<input type="text" name="name" required/>
<input type="text" name="lastname" required/>
<input type="text" name="username" required/>
<input type="text" name="email" required/>
<input type="password" name="password" required/>
<input type="button" id="submitBtn" value="submit"/>
</form>
<div id="response"></div>
<script>
$(function() {
$("#submitBtn").on("click", function(e) {
e.preventDefault();
$.ajax({
url: 'http://stopfoodwaste.stefspakman.com/app/signup.php',
type: 'POST',
data: $('#myform').serialize(),
beforeSend: function() {
$("#message").html("sending...");
},
success: function(data) {
if(data.status === "success"){
$("#message").hide();
$("#response").html(data);
alert("succes");
location.reload();
}
else if(data.status === "exist"){
$("#message").hide();
alert("Dit emailadress is reeds in gebruik, probeer in te loggen of gebruik een ander mailadres.");
}
else if(data.status === "failed"){
alert("Something Went wrong");
}
}
});
});
});
</script>
</body>
</html>

Categories

Resources