I got a register form using bootstrap modal that will call an ajax post function.
however, it does not seems to execute my $.post.
Also, how do i use the return value from my php function into my ajax data? so if my createAccount returns true or some other value, how does my ajax capture it?
<form action="" id="registerForm" method="POST">
.....
<div class="d-grid gap-2">
<button class="btn btn-primary" id="btnRegister" type="submit">Register!</button>
</form>
my ajax.
$("#email").keyup(function(){
var email = $("#email").val()
{
$('#emailResult').remove();
$.post("createaccount.php",{
checkEmail : email
}, function(data){
if(data=="true")
{
error=true;
var str = '<div id="emailResult">';
str +='<div class="alert alert-danger" role="alert">';
str +='Email address already exists!';
str+= '</div></div>';
$('#result').append(str);
}
else
{
error="false";
}
});
}
});
$("#btnRegister").click(function(){
var email = $("#email").val();
var password = $("password").val();
$.post("createaccount.php",{
email : email,
password : password
},function(data){
alert(data);
})
});
my createaccount.php
<?php
include("db.php");
include("functions.php");
if(isset($_POST['checkEmail']))
{
$email = $_POST['checkEmail'];
{
if(checkEmailExists($email))
{
echo "true";
}
}
}
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$password = $_POST['password'];
if(createAccount($email,$password))
{
return true;
}
else
{
return false;
}
}
?>
my functions.php
function createAccount($email,$password)
{
global $conn;
$hashPassword = password_hash($password,PASSWORD_DEFAULT);
$sql = "INSERT into USERS (email,password) VALUES ('$email','$hashPassword')";
if(mysqli_query($conn,$sql))
{
return true;
}
else
{
echo mysqli_error($conn);
return false;
}
}
2
Answers
Try adding this
Instead of
This code will stop form from submitting on button click.
Btw for email checking use another true false value to prevent form submitting until mail validation result comes.
And later…
In order to get to the correct place in your PHP code you need to have a
submit
parameter in the POST arrayBut your AJAX call does not pass that parameter so add it
You could also use a
e.preventDefault();
to stop the browser submitting the form in the normal way as well as doing your AJAX call