Here is my code:
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function() {
$("#btnSubmit").click(function() {
$.ajax({
type: "POST",
url: "deepak.php",
datatype: "html",
data: 'Name=' + $("#name").val() + '&Email=' + $("#email").val() + '&password=' + $("#password").val() + '&cnfpassword=' + $("#cnfpassword").val(),
success: function(result) {
if (result == 'success') {
alert("Ajax Successfully Executed")
}
}
});
});
});
</script>
In my php code "success" message is generated via echo function. ajax works fine , it makes the required request. The only part is not working is the success
.
here is my server-side code :
<?php //Database credentials $dbHost = 'localhost'; $dbUsername = 'root'; $dbPassword = ''; $dbName = 'fmc';
//Connect and select the database $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($db){
echo 'connected'; } else {
echo "disconnected"; }
$name = $_POST['Name']; $email = $_POST['Email']; $password = $_POST['password']; $cnfpassword = $_POST['cnfpassword'];
$sql = "INSERT INTO seeifyouqualify (name, email, password, cnfpassword) VALUES ('$name', '$email', '$password', '$cnfpassword')";
$query = mysqli_query($db, $sql);
if(mysqli_query($db, $sql)){
echo "success"; } ?>
Instead of send all inputs data what you can do is send the form data serialized like this:
<script>
$(document).ready(function() {
var formData = $("form#yourformId").serialize();
$("#btnSubmit").click(function() {
$.ajax({
type: "POST",
url: "deepak.php",
datatype: "html",
data: {'data_name': formData},
success: function(result) {
if (result == 'success') {
alert("Ajax Successfully Executed")
}
}
});
});
});
</script>
Also what I did above is send the data with a name because we have to catch it in php
like:
<?php
if(isset($_POST['data_name'])){
//do something....
}
?>
It's important to use if(isset(...))
because let's say someone went to your php
page without submitting the form, so php
wont know what do you mean by $name = $_POST['name'];
Now, the last thing is, how to use the serialized data :
<?php
if(isset($_POST['data_name'])){
$get = explode('&', $_POST['data_name'] ); // explode with and
foreach ( $get as $key => $value) {
$valn[ substr( $value, 0 , strpos( $value, '=' ) ) ] = substr( $value, strpos(
$value, '=' ) + 1 ) ;
}
// access your query param
$name = $valn['name'];
$email = $valn['email'];
$password = $valn['password'];
$cnfpassword = $valn['cnfpassword'];
}
?>
As per your javascript if your result is String('success') then only alert will call. but in your php code you echo output multiple times while connection established and after execute query.So your alert() not working due to ajax response not match your condition.