0

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.

2
  • See this answer about posting json. stackoverflow.com/a/14794856/3585500
    – ourmandave
    Jan 4, 2019 at 12:51
  • @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
    Jan 4, 2019 at 12:55

1 Answer 1

3
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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.