1

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.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • 1
    That's because you aren't actually sending any `POST` data. key-value pairs in the URL always translate to `GET` parameters; if you want to send `POST` data, you need to put it in your `send()` call: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send – Chris G Dec 24 '17 at 00:32
  • Possible duplicate of [Send POST data using XMLHttpRequest](https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest) – Chris G Dec 24 '17 at 00:34
  • 1
    What they said. And you really really really have to check out this thing called prepared statements.(your php is unsafe) – René Dec 24 '17 at 01:51
  • 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); – Jamie Ricketts Dec 24 '17 at 01:55
  • Use `$_REQUEST['accommodation']` it will parse the value of `GET` or `POST` requests in `php` - http://php.net/manual/en/reserved.variables.request.php – Pedro Lobito Dec 24 '17 at 02:30
  • `echo json_encode(header("HTTP/1.1 201 Created"));` — Unrelated to your actual problem, the `header()` function doesn't return a useful value. You should put a real response body there. – Quentin Dec 24 '17 at 19:34

4 Answers4

1

The problem here is that PHP's $_POST and $_GET don't have a great deal to do with the HTTP methods POST and GET.

$_POST contains data from the request body. $_GET contains data from the query string of the URL.

You are encoding the data in the query string of the URL, so it will appear in $_GET.

You need to put it in the body instead. You should set the right Content-Type request header (application/x-www-form-urlencoded which is the default format used by a form submission and the one you are using already) so PHP knows how to decode the data you've sent. You should also properly escape special characters too.

xhr2.open("POST" , "task2.php");
xhr2.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
var body = "accommodation=" + encodeURIComponent(a) + 
           "&username=" + encodeURIComponent(b) + 
           "&accid=" + encodeURIComponent(c) + 
           "&npeople=" + encodeURIComponent(d) + 
           "&date=" + encodeURIComponent(e);
xhr2.send(body);
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
0

This is happening because you are not putting the data in the request body. You are appending it to the url. you should use post like this:

  var http = new XMLHttpRequest();
  var url = "get_data.php";
  var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", 
"application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) 
{
        alert(http.responseText);
   }
}
 http.send(params);

taken from here: Send POST data using XMLHttpRequest

I didn't know this could work 1+ for this cool mistake it may be useful to send some separate control data

Amr Berag
  • 1,002
  • 7
  • 14
-1

I personally don't prefer to use JQuery, too. Because the native Javascript is able to handle everything or even more.

For your situation, you should write

xhr2.open("POST", "task2.php", true);
xhr2.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // crucially important!
xhr2.send("accommodation=" + a + "&username=" + b + "&accid=" + c + 
        "&npeople=" + d + "&date=" + e);

This should work, you may ask further questions about AJAX. I wrote my own library for manipulating AJAX.

L. Cang
  • 47
  • 6
-2

Why not just use jquery ajax function.
You can try this and i hope it works for you.

var a = $('#accommodation').val();
var b = $('#username').val();
var c = $('#accid').val();
var d = $('#npeople').val();
var e = $('#date').val();
$.ajax({
        url:'task2.php',
        type:'post',
        data:{accommodation:a,username:b,accid:c, npeople:d, date:e},
        dataType:'json',
        success:function(response){
            console.log(response);
        }
    });
joe M
  • 61
  • 1
  • 4