Getting data back from a PHP script - javascript

So after validating the form via Jquery, I like to know if the username and password are valid. If they are, it should redirect to another page, else I want to find a way of showing it to the user. At this point, I'm really confused. Here's the jquery code:
$(document).ready(function(e) {
$('.error').hide();
$('#staffLogin').submit(function(e) {
e.preventDefault();
$('.error').hide();
uName = $('#staff_username').val();
pWord = $('#staff_password').val();
if(uName == ''){
$('#u_error').fadeIn();
$('#staff_username').focus();
return false;
}
if(pWord == ''){
$('#p_error').fadeIn();
$('#staff_password').focus();
return false;
}
$.ajax({
type : 'POST', url : 'staff_access.php', data : 'uName='+uName+'&pWord='+pWord,
success: function(html){
if(html == 'true'){
window.location = 'staff_page.php';
}
else{
$('#val_error').fadeIn();
}
}
})
});
});
PHP:
<?php
include('admin/config.php');
$username = $_POST['uName'];
$password = $_POST['pWord'];
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
if ($conn) {
$qry = "SELECT lastname, firstname, FROM staff_user WHERE username='".$username."' AND pass='".$password."";
$res = mysqli_query($qry);
$num_row = mysqli_num_rows($res);
$row=mysql_fetch_assoc($res);
if ($num_row == 1) {
session_start();
$_SESSION['login'] = true;
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['username'] = $row['username'];
echo "true";
}
else{
echo "false";
}
}
else{
$conn_err = "Could not connect.".mysql_error();
}
mysqli_close($conn);
?>
FORM:
<form name="staff_login" method="post" action="" id="staffLogin">
<fieldset>
<legend>Staff Login</legend>
<span class="fa fa-user fa-5x"></span>
<br><br>
<input type="text" name="staff_username" id="staff_username" placeholder="Username">
<br><span class="error" id="u_error">Username Required</span><br>
<input type="password" name="staff_password" id="staff_password" placeholder="Password">
<br><span class="error" id="p_error">Password Required</span><br>
<span class="error" id="val_error">Incorrect Username and Password combination</span>
<input type="submit" name="staff_login" value="Login">
</fieldset>
</form>

Your ajax data is sent in wrong format. POST data should be sent as an object.
$.ajax({
type : 'POST',
url : 'staff_access.php',
data : {
uName: uName,
pWord: pWord
},
dataType: 'text',
success: function(html){
if(html == 'true'){
window.location = 'staff_page.php';
}
else{
$('#val_error').fadeIn();
}
}
});
Also avoid using texts like 'html'. You may end up getting unnecessary errors due to that.
Use more relevant words like "success: function(response)"

Try to define a dataTpe in your ajax config - dataType: "html"

Related

Ajax validation duplicates html page inside html element

My PHP username validation with Ajax duplicates my html page inside of html div(this is for showing ajax error) element. I tried some solutions and google it bu can't find anything else for solution. Maybe the problem is about the $_POST but I also separated them in php (all the inputs validation).
Here is PHP code
<?php
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
$infoun[] = 'Your username has at least 6 alphanumeric characters';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['username'])){
$errorun[] = 'This username is already in use';
}
}
}
if(isset($_POST['fullname'])){
//fullname validation
$fullname = $_POST['fullname'];
if (! $user->isValidFullname($fullname)){
$infofn[] = 'Your name must be alphabetical characters';
}
}
if(isset($_POST['password'])){
if (strlen($_POST['password']) < 6){
$warningpw[] = 'Your password must be at least 6 characters long';
}
}
if(isset($_POST['email'])){
//email validation
$email = htmlspecialchars_decode($_POST['email'], ENT_QUOTES);
if (! filter_var($email, FILTER_VALIDATE_EMAIL)){
$warningm[] = 'Please enter a valid email address';
} else {
$stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['email'])){
$errorm[] = 'This email is already in use';
}
}
}
?>
Here is Javascript
<script type="text/javascript">
$(document).ready(function(){
$("#username").keyup(function(event){
event.preventDefault();
var username = $(this).val().trim();
if(username.length >= 3){
$.ajax({
url: 'register.php',
type: 'post',
data: {username:username},
success: function(response){
// Show response
$("#uname_response").html(response);
}
});
}else{
$("#uname_response").html("");
}
});
});
</script>
<input type="text" name="username" id="username" class="form-control form-control-user" placeholder="Kullanıcı Adınız" value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username'], ENT_QUOTES); } ?>" tabindex="2" required>
<div id="uname_response" ></div>
Here is the screenshot:
form duplicate screenshot
The only code in your PHP file should be within the <?php ?> tags. You need to seperate your PHP code into another file.

Email Live Checking PHP and Mysql

I have an issue im stuck for 3 days. Im trying to check in DB if the email the user is entering is already registered and avoid registering in duplicate. But this doesn't seem to work fine
here is my code:
This is in the HTML
<script type="text/javascript">
$(document).ready(function() {
$("#cf_email").keyup(function(e) {
var uname = $(this).val();
if (uname == "")
{
$("#msg").html("");
$("#Submit").attr("disabled", true);
}
else
{
$("#msg").html("Verificando, espere...");
$.ajax({
url: "check_availability.php",
data: {Email: uname},
type: "POST",
success: function(data) {
if(data.status == true) {
$("#msg").html('<span class="text-danger">Email ya registrado!</span>');
$("#Submit").attr("disabled", true);
} else {
$("#msg").html('<span class="text-success">Email Disponible para Registrar!</span>');
$("#Submit").attr("disabled", false);
}
}
});
}
});
});
</script>
<right><form id="register" action="contact.php" method="post">
<p><label>E-mail para Registro</label></p>
<input type="text" name="cf_email" id="cf_email" title="Email" class="demoInputBox" placeholder="Email Valido" required><div id="msg" class="form-group"></div>
</form></right>
this is the check_availability.php
$con = mysqli_connect($host, $user, $pass, $db) or die("Error " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_POST["cf_email"]) && $_POST['cf_email'] != '')
{
$response = array();
$cfmail = mysqli_real_escape_string($con,$_POST['cf_email']);
$sql = "select Email from Bares where Email='".$cfmail."'";
$res = mysqli_query($con, $sql);
$count = mysqli_num_rows($res);
if($count > 0)
{
$response['status'] = false;
$response['msg'] = 'email already exists.';
}
else
{
$response['status'] = true;
$response['msg'] = 'email is available.';
}
echo json_encode($response);
}
?>
it doesn't matter which email i introduce in the textfield because always says its available even if the email is registered already in the database
In your JS you're processing a string, not an object. You need to parse it:
success: function(data) {
dataObj = JSON.parse(data);
if(dataObj.status == true) {
....
This is an Example with mysqli OOP try it will work without Problem:
PHP:
<?php $mysqli=new mysqli($host, $user, $pass, $db); mysqli_set_charset($mysqli,'utf8');
if (!empty($_POST['cf_email'])){
extract($_POST);
$sql=$mysqli->query("select Email from Bares where Email='".$cf_email."'");
if($sql->num_row>0){
$status=1;
}
else{
$status=0;
}
echo $status;
die;}
?>
HTML:
<right>
<form id="register" action="contact.php" method="post">
<p><label>E-mail para Registro</label></p>
<input type="text" name="cf_email" id="cf_email" title="Email" class="demoInputBox" placeholder="Email Valido" required>
<input type="submit" id="submit">
<div id="msg" class="form-group"></div>
</form>
</right>
JS:
<script type="text/javascript">
$(document).ready(function() {
$("#cf_email").keyup(function(e) {
var uname = $(this).val();
if (uname == "") {
$("#msg").html("");
$("#submit").attr('disabled', true);
} else {
$.ajax({
url: "check_availability.php",
data: $(this).serialize(),
type: "POST",
success: function(data) {
if (data == 1) {
$("#msg").html('<span class="text-danger">Email ya registrado!</span>');
$("#submit").attr('disabled', true);
} else {
$("#msg").html('<span class="text-success">Email Disponible para Registrar!</span>');
$("#submit").attr('disabled', false);
}
}
});
}
});
});
</script>

Ajax call php function breaks all javascript functions and page

I'm trying to validate if a username is already taking or not. This onchange of an input field. I already got other checks but they don't work anymore since I added the ajax call. I'm new to ajax and javascript so the error can be there.
the html form:
<form action="test" method="post">
<input id="username" type="text" placeholder="Gebruikersnaam" name="username" required onchange="checkUserName()">
<br>
<input id="email" type="text" placeholder="Email" name="email" required onchange="validateEmail()">
<br>
<input id="pass1" type="password" placeholder="Type wachtwoord" name="password1" required>
<br>
<input id="pass2" type="password" placeholder="Bevestig wachtwoord" name="password2" required onchange="passwordCheck()">
<br>
<select name="typeAccount">
<option value="bedrijf">Bedrijf</option>
<option value="recruiter">Recruiter</option>
<option value="werkzoekende">Talent zoekt job</option>
</select>
<p id="demo1">
</P>
<p id="demo2">
</P>
<button type="submit">Scrijf mij in!</button>
</form>
the javascript that I use:
<script src="jquery.js">
function passwordCheck(){
var password1 = document.getElementById('pass1').value;
var password2 = document.getElementById('pass2').value;
if(password1 !== password2){
document.getElementById("pass1").style.borderColor = "#ff3333";
document.getElementById("pass2").style.borderColor = "#ff3333";
}else{
document.getElementById("pass1").style.borderColor = "#1aff1a";
document.getElementById("pass2").style.borderColor = "#1aff1a";
}
}
function validate(email){
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validateEmail(){
var email = document.getElementById('email').value;
if(validate(email)){
document.getElementById("email").style.borderColor = "#1aff1a";
}else{
document.getElementById("email").style.borderColor = "#ff3333";
}
}
function checkUserName(){
var username = document.getElementById('username').value;
if(username === ""){
document.getElementById("username").style.borderColor = "#ff3333";
}else{
$.ajax({
url: "userCheck.php",
data: { action : username },
succes: function(result){
if(result === 1){
document.getElementById("username").style.borderColor = "#1aff1a";
}else{
document.getElementById("username").style.borderColor = "#ff3333";
}
}
});
}
}
</script>
The php script I use this is in a different file:
<?php
include("connect.php");
$connect = new Connect();
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query('select username from usermaindata where username = "'. $username .'"');
if(mysql_num_rows($result)>0){
echo 0;
}else{
echo 1;
}
?>
The script and the html form is in the same html-file and the php is in a seperate PHP-file.
I just want to check if the name is already in the database or not.
I assume your database connection is perfect.
$username = mysql_real_escape_string($_POST['username']);
change above code to
$username = mysqli_real_escape_string($db_connection,$_REQUEST['action']);
because in your ajax you're doing like
$.ajax({
url: "userCheck.php",
data: { action : username },
succes: function(result){
if(result === 1){
document.getElementById("username").style.borderColor = "#1aff1a";
}else{
document.getElementById("username").style.borderColor = "#ff3333";
}
}
});
You have not specified request type and you're fetching value using $_POST with different variable name username which is actually value
You should use $_REQUEST['action']
And make sure you've added jquery.js file in your html.

jQuery after submit data doesnt show succes view, but data input to database

i have a little problem here with jQuery.
i have made a submit form with this following code :
<form class="form-inline" id="newslatter" role="form" >
<select name="city" id='city' class="form-control">
<option value="<?=$id?>">Singapore</option>
</select>
<input type="email" class="form-control" name="email" id="email" placeholder="<?=$this->lang->line('footer_enter_email')?>" value="<?=(isset($json)?$json["email"]:"")?>">
<label id="emptyemail" style="color:indianred"><?php echo form_error('email'); ?></label>
<button type="submit" class="btn btn-success input"><?=$this->lang->line('footer_signup_now')?></button>
</form>
<div id="register_complete" style="display: none;color:whitesmoke;">
<p align="center">Congratulations, You have been added to our Newsletter
Thank you for your registration. From now on you will receive updates about exclusive offers in your city.</p>
</div>
and this is my jQuery :
<script type="text/javascript">
function validateEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$("#newslatter").submit(function(e){
e.preventDefault();
var email= $("#email").val();
var city=$("#city").val();
var something_wrong="";
var agreement = $('#agreement input[type="checkbox"]').is(":checked");
if(email.length == 0){
$("#emptyemail").html("Please fill in Email field");
$("#email").focus();
something_wrong=true;
}else if(!validateEmail(email)){
$("#emptyemail").html("insert valid email address!");
something_wrong=true;
}else{ $("#emptyemail").html(""); something_wrong=false; }
if(agreement == false ){
$("#notagree").html("You should read and accept Terms and conditions and Privacy Policy");
something_wrong=true;
}else{ $("#notagree").html(""); something_wrong=false;}
if( something_wrong == true) return false;
jQuery.ajax({
type: "POST",
url: "ajax/newslatter",
dataType: 'json',
data: {pcity:city,pemail:email},
success: function(res) {
if (res)
{
if(res.message != "success"){
$("#emptyemail").html(res.message);
return false;
}else{
$("#newslatter").hide();
$("#register_complete").show();
}
}
}
});
return false;
});
and this is my ajax controller:
Function newslatter(){
$city_id=$this->input->post('pcity',true);
$email = $this->input->post("pemail",true);
$query= $this->ajax_m->m_check_email($email);
if(strlen($email)==0){
$data["message"]= "Please fill in Email field";
}else{
if($query != null){
$data["message"]= "E-mail already registered";
}else{
$this->ajax_m->m_insert_newslatter($city_id,$email);
$data["message"]= "success";
}
}
}
and here is the following model for ajax :
Function m_check_email($email){
$sql="SELECT `email` FROM `uhd_newslatter` WHERE `email` = '$email'";
$query=$this->db->query($sql)->row_array();
return $query;
}
Function m_insert_newslatter($city,$email){
$sql="INSERT INTO `uhd_newslatter` (`singapore_address_id` , `email`) VALUES ($city,'$email')";
$this->db->query($sql);
}
those are all my code. my problems are :
if i submit data, data send into my database, but after that there is nothing happening in my view, actually if submit process is success there will be show my success message, and all my submit form will be hide
and, if i use the same email, if i submit it, it should be show a message that i put it ajax controller. but data isn't input to database.
guys can you help me whats wrong on my code?
sorry if i have so many part of code (:
In your ajax writen dataType:'json', but in your controller there is json_encode($yourdata); that will be read in success ajax. Because of that, your success is not executed.
jQuery.ajax({
type: "POST",
url: "ajax/newslatter",
dataType: 'json',
data: {pcity:city,pemail:email},
success: function(res) { //controller has to make json_encode($data); for product res value.
if (res)
{
if(res.message != "success"){
$("#emptyemail").html(res.message);
return false;
}else{
$("#newslatter").hide();
$("#register_complete").show();
}
}
}
});
Your controller need to be added echo json_encode($data);
Function newslatter(){
$city_id=$this->input->post('pcity',true);
$email = $this->input->post("pemail",true);
$query= $this->ajax_m->m_check_email($email);
if(strlen($email)==0){
$data["message"]= "Please fill in Email field";
}else{
if($query != null){
$data["message"]= "E-mail already registered";
}else{
$this->ajax_m->m_insert_newslatter($city_id,$email);
$data["message"]= "success";
}
}
echo json_encode($data);//add this line
}
Please update your newsletter function with this code:
function newslatter(){
$data =array();
$city_id=$this->input->post('pcity',true);
$email = $this->input->post("pemail",true);
$query= $this->ajax_m->m_check_email($email);
if(strlen($email)==0){
$data["message"]= "Please fill in Email field";
}else{
if($query != null){
$data["message"]= "E-mail already registered";
}else{
$this->ajax_m->m_insert_newslatter($city_id,$email);
$data["message"]= "success";
}
}
return json_encode($data);
}

back-end error_msg is not giving a alert..!

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

Categories

Resources