简体   繁体   中英

AJAX form posting to PHP script but $_POST is empty in PHP script

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.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM