0
votes

Ajax form posting to php script but $_POST is empty in php script

I have a contact us form which posts data via ajax. On form submit ajax posts data to a PHP script however the $_POST is always empty in the PHP script. Headers are sent, request payload has all the post information that I need but still, $_POST is empty in the PHP script.

HTML Form

<form action="contact.php" method="post" novalidate="novalidate" 
id="contact-form">
<input name="name" id="name" type="text" value="" >
<input type="text" name="address" id="address" value="" >
<input type="submit" value="Send" id="submit_contact">
</form>

JQUERY

       $.ajax({
        type: 'POST',
        url: 'contact.php',
        dataType: 'json',
        contentType: 'application/json',
        cache: false,
        data: $('#contact-form').serialize(),
        success: function(data) {
            if(data.info !== 'error'){                  
             //success
            } else {
                console.log(JSON.stringify(data));
                //failure
            }
        }
    });

PHP

if(isset($_POST['name']) and isset($_POST['address']))){
      //Process
} else {
  //success
}

$_POST always returns null but I want to get the name and address posted values.

1
See this answer about posting json. stackoverflow.com/a/14794856/3585500ourmandave
@ourmandave — That's about parsing POSTed JSON, but since the code in the question isn't POSTing JSON in the first place, it doesn't really help.Quentin

1 Answers

3
votes
contentType: 'application/json',

You claim you are POSTing JSON, which PHP doesn't have a default parser for, so PHP doesn't try to parse it and doesn't populate $_POST.

Since you aren't POSTing JSON ($('#contact-form').serialize() returns URL encoded data, not JSON) simply remove the lie and it will work.