The PHP code for login validation works properly when run from the html page by using form action but when run using ajax script it fails to load.
PHP code not involving database seems to run fine though.
JavaScript
< script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" > < /script> <
script >
$(document).ready(function() {
$("#login").submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
var postForm = { //Fetch form data
'name': $('input[name=name]').val(),
'password': $('input[name=password]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type: 'POST', //Method type
url: '.php', //Your form processing file url
data: postForm, //Forms name
dataType: 'json',
success: function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name).append('<p>' + data.error + '</p>'); //Throw relevant error
alert("Nope");
}
} else {
$('#success').fadeIn(1000).append('<p>' + data.name + '</p>'); //If successful, than throw a success message
alert("yes");
}
}
});
event.preventDefault(); //Prevent the default submit
});
}); < /script>
PHP Code
<?php
$errors = array();
$form_data = array();
include("config.php");
if (session_status() == PHP_SESSION_NONE) {
session_start();}
else{
$_SESSION['ses']="Already in session":
/* Write already in session code */
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT * FROM users WHERE user_name = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if (empty($_POST['name'])) { //Name cannot be empty
$errors['name'] = 'Name cannot be blank';
}
if (!empty($errors)) { //If errors in validation
$form_data['success'] = false;
$form_data['errors'] = $errors;
}
else{
if($count == 1) {
$_SESSION['login_user'] = $myusername;
}else {
$error = "Your Login Name or Password is invalid";
$_SESSION["error"] = $error;
}
}
}
echo json_encode($form_data);
?>