PHP not receiving AJAX POST from js File

Viewed 60

I have been trying to work this out for hours now and cannot find any answer that helps me.

This is the code in my javascript file

function sendMovement(cel) {
  var name = "test";
  $.ajax({
      type: 'POST',
      url: '../game.php',
      data: { 'Name': name },
      success: function(response) {
          console.log("sent");
      }
  });
}

This is the code from my PHP file (it is outside the js file)

if($_SERVER["REQUEST_METHOD"] == "POST") {
  $data = $_POST['Name'];
  console_log($data);
}

When debugging I can see that AJAX is sending a POST and it does print in the console "SENT" but it does not print $data

update: the function console_log() exists in my PHP file and it works

2 Answers

Try getting response in JSON format, for that your js should have dataType:'JSON' as shown below

JS Code:-

function sendMovement(cel) {
  var name = "test";
  $.ajax({
      type: 'POST',
      dataType:'JSON',   //added this it to expect data response in JSON format
      url: '../game.php',
      data: { 'Name': name },
      success: function(response) {
          //logging the name from response
          console.log(response.Name);
      }
  });
}

and in the current server side code you are not echoing or returning anything, so nothing would display in ajax response anyways.

changes in php server code:-

if($_SERVER["REQUEST_METHOD"] == "POST") {
  
  $response = array();
  $response['Name'] = $_POST['Name'];
  //sending the response in JSON format
  echo json_encode($response);

}

I fixed it by doing the following:

To my game.php I added the following HTML code (for debugging purposes)

<p style = "color: white;" id="response"></p>

Also added in my game.php the following

if($_SERVER["REQUEST_METHOD"] == "POST") {
  
  $gameID = $_POST['gameID'];
  $coord = $_POST['coord'];
  $player = $_POST['player'];

  echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;

}

AND in my custom.js I updated

function sendMovement(cel) {
  var handle = document.getElementById('response');
  var info = [gameID, cel.id, current_player];

  $.ajax({
    type: 'POST',
    url: '../game.php',
    data: {
      gameID: info[0],
      coord: info[1],
      player: info[2]
    },
    success: function(data) {
      handle.innerHTML = data;
    },
    error: function (jqXHR) {
      handle.innerText = 'Error: ' + jqXHR.status;
    }
  });
}
Related