im a beginner coder and i want to make a contact form sending a json object to another php file. This is my current code
[...]
<body>
<form id="form" class="formular">
<div class="input-group">
<input id="phone" type="tel" class="form-control" name="phone" placeholder="phone" required>
</div>
<br>
<div class="input-group">
<input type="email" id="email" class="form-control" name="email" placeholder="mail" required>
</div>
<br>
<div class="input-group">
<textarea id="message" class="form-control" placeholder="message..." required></textarea>
</div>
<button id="form_submit_button" name="form_submit_button">Send!</button>
</form>
</body>
</html>
<?php
?>
<script>
jQuery(document).ready(function($) {
$("#form_submit_button").click(function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'test.php',
data: JSON.stringify({ Form: $('#form').val }),
contentType: "application/json; charset=utf-8",
dataType: "json",
})
});
});
</script>
The test.php simly is: var_dump($_POST);
Of course it’s always 0. Can someone help me please 🙂
3
Answers
Try instead
$('#form').serialize()
.You may also use FormData.
You are not forced to use jquery, here is a possible way using fetch native javascript.
What you’re trying to do is to send the contents of the form using AJAX. As pointed out by NVRM, you don’t need to use jQuery to do this. You can use the native fetch function.
First, you put the values of each of the form fields into variables, and then insert them into a
FormData
object. Then use thefetch
function to send theFormData
object to the server where it can be accessed from the$_POST
variable.What you had originally was
$('#form').val()
which doesn’t return anything because#form
is the form element, which doesn’t have a value.