When I try to POST form data obtained by form.serialize() using jQuery Ajax, the data is not being correctly sent to action page.
I even tried alert(data); to check if data is being stored in the variable. And it is being stored but somehow not being sent to contact.php correctly. The action page responds as if no data is being sent to it.
Also, there are no errors in contact.php. It is fully functional. I'm actually migrating the client side page to Bootstrap 5. It is working correctly in the old Bootstrap 4 page.
Here's my code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css" integrity="sha512-usVBAd66/NpVNfBge19gws2j6JZinnca12rAe2l+d+QkLU9fiG02O1X8Q6hepIpr/EYKZvKx/I9WsnujJuOmBA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
.grecaptcha-badge {
visibility: hidden;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/js/bootstrap.bundle.min.js" integrity="sha512-72WD92hLs7T5FAXn3vkNZflWG6pglUDDpm87TeQmfSg8KnrymL2G30R7as4FmTwhgu9H7eSzDCX3mjitSecKnw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://www.google.com/recaptcha/api.js?render=6LcCwcIbAAAAAMTsXtGwnfHIPWOMc5aLQZ4RME0a"></script>
<script>
$(document).ready(function(){
$("#contactForm").submit(function(event){
event.preventDefault();
var form = $(this);
var url = form.attr("action");
grecaptcha.ready(function() {
grecaptcha.execute('6LcCwcIbAAAAAMTsXtGwnfHIPWOMc5aLQZ4RME0a', {action: 'submit'}).then(function(token) {
$("#recaptchaResponse").val(token);
var data = form.serialize();
alert(data); // Just to check if data is stored to variable...
$.ajax({
type : "POST",
url : url,
data : data,
success : function(response) {
$("#formResponse").html(response);
}
})
});
});
});
});
</script>
<div class="row">
<div class="col"></div>
<div class="container col border bg-light">
<form id="contactForm" class="p-3" action="contact.php">
<div class="mb-3">
<label for="name">Name :</label>
<input class="form-control" name="name" placeholder="Your name...">
</div>
<div class="mb-3">
<label for="email">Email :</label>
<input class="form-control" name="email" placeholder="Your email...">
</div>
<div class="mb-3">
<label for="message">Message :</label>
<input class="form-control" name="message" placeholder="Write something...">
</div>
<input type="hidden" name="recaptchaResponse" id="recaptchaResponse">
<button type="submit" id="submitButton" class="btn btn-primary">Send</button>
<div id="formResponse" class="pt-3"></div>
</form>
</div>
<div class="col"></div>
</div>
</body>
</html>
contact.php :
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'mailer/Exception.php';
require 'mailer/PHPMailer.php';
require 'mailer/SMTP.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = 'smtp';
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->Host = 'smtp.gmail.com';
$mail->Username = '[email protected]';
$mail->Password = 'app_password';
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['text']) && !empty($_POST['name']) && !empty($_POST['email'])) {
if (isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$captcha = $_POST['recaptchaResponse'];
$verifyCaptcha = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=secret_key&response='.$captcha.'&remoteip='.$ip);
$captchaData = json_decode($verifyCaptcha);
$score = $captchaData -> score;
if ($captchaData -> success = true && $captchaData -> score > 0.5) {
$mail->IsHTML(true);
$mail->AddAddress($email, $name);
$mail->SetFrom('[email protected]', 'User 1');
$mail->AddReplyTo('[email protected]', 'User 1');
$mail->AddBCC('[email protected]', 'User 2');
$mail->Subject = 'Contact Form';
$content = 'Your query has been sent successfully. Please wait 48 working hours for response. (Message : '.$message.')';
$mail->MsgHTML($content);
if(!$mail->Send()) {
echo '<p class="alert alert-danger">Error while sending query.</p>';
var_dump($mail);
} else {
echo('<p class="alert alert-success">Form submitted successfully.<br>(Captcha Score : '.$score.')</p>');
}
} else {
echo('<p class="alert alert-danger">Unable to verify captcha.</p>');
}
} else {
echo('<p class="alert alert-warning">reCAPTCHA data not received.</p>');
}
} else {
echo('<p class="alert alert-warning">Please fill all the required fields.</p>');
}
?>
Should I convert the data before posting with ajax? Any help will be greatly appreciated.
Edit : Added server side code too..


contact.php. Edit your question, add the minimal parts of that file which demonstrate the problem. Have you checked your browser's devtools and inspected the network request? Any errors on the console?contact.phpdue to some limitations. What it does is, it ensures Name and Email are filled, verifies recaptcha response and emails the contact details to client and me. I guess problem is not withcontact.php. There might be some encoding/decoding issue with the data.Please fill all the required fields.is the response fromcontact.php.contact.php.