Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TuffRivers's avatar

Empty $_POST array JS to PHP AJAX

No clue why this is happening, i have a form on my website that i submit to a php script using JQUERY and the $_POST is always empty but if i console.log the payload it shows in my console AND in the request in my network tab on chrome - so it looks like its being sent (i can confirm it says its a post request)

var result = {};
  $.each($('#cta-form').serializeArray(), function () {
    if(this.name){
      result[this.name] = this.value;
    }
  });

  var json = JSON.stringify(result);
  console.log(json); //this works

  request = $.ajax({
      url: 'https://mywebsite.ca/email.php',
      method: 'post',
      contentType: 'application/json',
      data: json
  });

my php file

$error = NULL;

if(empty($_POST["name"])) {
    $error .= "<li>Name is required</<li>";
} else {
    $name = $_POST["name"];
}

if(empty($_POST["email"])) {
    $error .= "<li>Email is required</li>";
} else if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
    $errorG .= "<li>Invalid email format</li>";
}else {
    $email = $_POST["email"];
} 

if(empty($_POST["phone"])) {
    $error .= "<li>Phone is required</li>";
} else {
    $phone = $_POST["phone"];
}


if(empty($_POST["message"])) {
    $error .= "<li>Message is required</li>";
} else {
    $message = $_POST["message"];
}
 
if(is_null($error)){
//send email and sent 200 code
       http_response_code(200);
        
       exit;
}

//this always sends because $_POST is empty so its adding tot he error message
http_response_code(412);
echo $error;
exit;

0 likes
7 replies
tykus's avatar

Why is data a string, and not an object? Lose this line:

var json = JSON.stringify(result);

and send result Object instead:

  request = $.ajax({
      url: 'https://mywebsite.ca/email.php',
      method: 'post',
      contentType: 'application/json',
      data: result
  });
tykus's avatar

@TuffRivers what does result look like before making the request. Can you inspect the outgoing Request in the browser's network tab; is the payload correct; what does it look like?

sr57's avatar

Are you sure $_POST is empty?

To be tested with empty($_POST)

and test $_POST['jdon'] (from your OP) and 'result' from @tykus example

sr57's avatar

@TuffRivers

Ok, but you have 2 pbs , first you did not send an object, follow @tykus example.

and second you did not test the right post variable

Please or to participate in this conversation.