I'm using AJAX to take in form data and send it using the POST method to the web service. I'm trying to use $a = $_POST["accommodation"]
to retrieve the information as it will be changing data on the database. It works when the ajax method is set to POST
or GET
and the web service is using
$a = $_GET["accommodation"]
but not $a = $_POST["accommodation"]
.
JS:
function ajaxrequest()
{
var xhr2 = new XMLHttpRequest();
xhr2.addEventListener ("load", (e) =>
{
var output = ""; // initialise output to blank text
var data = JSON.parse(e.target.responseText);
output = data;
if(e.target.status==201)
{
document.getElementById('response').innerHTML = "Successfuly booked!"
}
else if(e.target.status=404)
{
document.getElementById('response').innerHTML = "Sorry fully booked for this date!"
}
});
var a = document.getElementById("accommodation").value;
var b = document.getElementById("username").value;
var c = document.getElementById("accid").value;
var d = document.getElementById("npeople").value;
var e = document.getElementById("date").value;
xhr2.open("POST" , "task2.php?accommodation=" + a + "&username=" + b + "&accid=" + c + "&npeople=" + d + "&date=" + e);
xhr2.send();
}
PHP
header("Content-type: application/json");
$a = $_POST["accommodation"];
$b = $_POST["npeople"];
$c = $_POST["date"];
$d = $_POST["username"];
$e = $_POST["accid"];
$conn = new PDO ("mysql:host=localhost;dbname=***;", "***", "***");
$result = $conn->query("select * from acc_dates where accid=$e and thedate=$c");
$row = $result->fetch();
if($row["availability"] >= $b)
{
echo json_encode(header("HTTP/1.1 201 Created"));
$result = $conn->query("insert into acc_bookings (accID, thedate, username, npeople) values ($e, $c, '$d', $b)");
$result = $conn->query("update acc_dates set availability = availability + -$b where accid=$e and thedate=$c");
}
else
{
echo json_encode(header("HTTP/1.1 404 Not Found"));
}
I tried doing the following but still isnt working?
xhr2.open("POST" , "task2.php");
xhr2.send("accommodation=" + a + "&username=" + b + "&accid=" + c +
"&npeople=" + d + "&date=" + e);
also I cant use jquery.