简体   繁体   中英

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:

<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>
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>

Here is my Jquery Ajax call:

<script>
$(document).ready(function() {
$('form').submit(function(event) {
var formData = $("form").serialize();
console.log(formData); 
$.ajax({
type: 'POST', 
url: 'form.php', 
data: formData, 
dataType: 'json', 
encode: true    
   })
.done(function(data) {
 console.log(data); 
 });
 event.preventDefault();
 });

 });


</script>

And here is my PHP page:

if(isset($_POST['formData']))    
$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM