0

I'm doing a simple post request, but my server says the post request has no body. Every key has an "undefined" value. Here is my post request:

let alert_title = 'Alert';
let alert_body = 'Alert';
let show_alert = 4;

console.log(handlePost(show_alert));

function handlePost(showAlert) {
  var params = new Object();
  params.alert_id = 1;
  params.alert_title = alert_title;
  params.alert_body = alert_body;
  params.show_alert = Number(show_alert);
  params.database_host = "my.ip.address";
  params.database_name = "my-database-name";
  console.log(params);

  $.ajax({
    type: "POST",
    url: "https://mydomain/api/UpdateAlert",
    data: params, 
    ContentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function (data) {
      console.log(data)
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

What am I doing wrong?

SuperDJ
  • 7,488
  • 11
  • 40
  • 74
user13989216
  • 19
  • 1
  • 4
  • 1
    first of all, there is an easy way to write objects: `let params = { paramName: paramValue }`. secondly, try removing the contentType and dataType properties from the $.ajax function – Albert Logic Einstein May 28 '21 at 18:32
  • You send the data as FormData. Maybe your server expect it as JSON-serialized payload. – Sven Eberth May 28 '21 at 18:32
  • I made both changes and the changes, but the values are still showing undefined on the server. I'm trying to get the values this way: const { database_host, database_name, alert_id, alert_title, alert_body, show_alert } = req.body; – user13989216 May 28 '21 at 18:38
  • How is this related to PHP?? – ADyson May 28 '21 at 19:26

1 Answers1

0

You are posting an object directly. Try to convert to JSON string before posting with JSON.stringify(params);

endeavour
  • 576
  • 4
  • 15