NL3
NL3

Reputation: 127

Sending data using Ajax to local PHP script, receive response but if-condition in php file is never met

I have a draggable div-container and whenever I drop it, its location is to be send to a local php script.

$(function() {
    $( "#fenster" ).draggable({
        stack: "#fenster", stop: function(event, ui){
            var pos_x = ui.offset.left;
            var pos_y = ui.offset.top;

            $.ajax({
                type: "POST",
                contentType: "application/json",
                data: {'x': pos_x},
                url: "index.php",
            }).done(function(msg){
                alert("data Saved: " + msg);
            });
        }
    });
});

In the php file (index.php) I check whether $_POST['x'] is set. Unfortunately, no matter what I do, the condition is never met.

  if((isset($_POST['x']))){
    $_SESSION['xLoc'] = $_POST['x'];
    echo "Test";
  }

Upon dropping the window, I get a response (alert of the msg shows output) and according to FireBug, the request DOES contain x.

Upvotes: 1

Views: 94

Answers (2)

NL3
NL3

Reputation: 127

I had two redirects that killed the POST request. After making adjustments to the if-conditions, this no longer happens and the data sent by the Ajax request is now also being successfully processed by PHP.

Thank you all that took the time to help me, it's greatly appreciated.

Upvotes: 0

Kylie
Kylie

Reputation: 11749

The PHP superglobal $_POST, is only available when you use these content types

    application/x-www-form-urlencoded (standard content type for simple form-posts) or
    multipart/form-data-encoded (mostly used for file uploads)

You are using application/json which means you need to get the stream with...

$rawData = file_get_contents("php://input");
$d = json_decode($rawData);
if((isset($d['x']))){
  $_SESSION['xLoc'] = $d['x'];
  echo "Test";
}

Or if you dont actually need to be submitting JSON, just remove the contentType from your jquery, and you should be able to retrieve the $_POST on the php side, using the code you already had.

$.ajax({
    type: "POST",
    data: {'x': pos_x},
    url: "index.php",
}).done(function(msg){
   alert("data Saved: " + msg);
 });

Or change your php to the code above, to retrieve the raw stream, if you need to be sending json data to the server

Upvotes: 2

Related Questions