Reputation: 51
I am trying to make an AJAX post to php but for some reason my PHP says that the post is empty. I don't get an error message from PHP or in my console. The alert(data)
at the end returns all the HTML in index.php
and the var_dump(post)
returns empty. first is the console.log(aantal) the second is console.log(data)
End of the console.log
script.js
$(document).ready(function () {
var date = "date";
var begin = "begin";
var eind = "eind";
var aantal = "aantal";
$('#datum').change(function () {
date = $("#datum").val();
console.log(date);
});
$('#beginTijd').change(function () {
begin = ($(this).val());
console.log(begin);
});
$('#Tijdsduur').change(function () {
eind = ($(this).val());
console.log(eind);
});
$('#aantalSloepen').change(function () {
aantal = ($(this).val());
console.log(aantal);
$.ajax({
type: "POST",
url: "index.php",
data: {
date: begin,
quantity: aantal
},
success: function (data) {
alert(data);
console.log(data);
}
});
});
});
index.php
<?php
var_dump($_POST);
$value1 = "";
$value2 = "";
if (isset($_POST['date'])) {
echo "Yes, mail is set";
$value1 = $_POST['date'];
$value2 = $_POST['quantity'];
} else {
echo "No, mail is not set";
}
echo $value1;
echo $value2;
Upvotes: 2
Views: 196
Reputation: 3050
You are calling index.php
file from the ajax and the index.php file is loaded on page load. So when you call the ajax it will return whole html code of index.php
to prevent that you have to add exit()
function to prevent execute further. See code below.
<?php
$value1 = "";
$value2 = "";
if (isset($_POST['date']) && isset($_POST['quantity'])) {
if (isset($_POST['date'])) {
echo "Yes, mail is set";
$value1 = $_POST['date'];
$value2 = $_POST['quantity'];
} else {
echo "No, mail is not set";
}
exit;
}
<html>
<!-- Your Code goes here -->
</html>
Upvotes: 1