How to get php page to receive ajax post from html page

I have a very simple form that has an input field for first name. I captured the form data and transmitted it via ajax to a PHP page using the standard jQuery posting method. However, I am not able at all get any responses from the PHP page that any data was captured on the server-side. I am not sure what I have done wrong or what is missing.

Here is my code.


<form action="process.php" method="POST">
<div class="form-group">
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
<div class="d-none" id="firstName_feedback">
<p>Please enter a first name.</p>
<button class="btn btn-primary" type="submit">Submit form</button>

Here is my Jquery Ajax call:

$(document).ready(function() {
$('form').submit(function(event) {
var formData = $("form").serialize();
type: 'POST', 
url: 'form.php', 
data: formData, 
dataType: 'json', 
encode: true    
.done(function(data) {



And here is my PHP page:

$ajaxData = ($_POST['formData']); 
echo $ajaxData;



In your Ajax function, you're passing the contents of formData to the server, though not as formData but as their original input name.

In this case, you have:

<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">

The input's name is firstName, so you need to call $_POST['firstName'] instead of $_POST['formData'].

if (isset($_POST['firstName'])) {
    $ajaxData = $_POST['firstName'];
    echo $ajaxData;

The same applies for any other field you would have in your form, so for example, having another input with the name lastName means you'd have to call $_POST['lastName'] to access it.

There were also some misplaced brackets and parentheses in the PHP code which I accommodated above.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.