Skip to content
Advertisement

$_POST remains null when posting through ajax with formData

This is the form:

<form id="complaintForm" enctype="multipart/form-data" method="POST">
    <input type="number" id="isComplaintForm" value="1" hidden>
    <label for="fname">Full Name</label><br />
    <input type="text" id="fname" name="fname"><br />
    <label for="DOB">Date of Birth</label><br />
    <input type="date" id="DOB" name="DOB"><br /><br />
    <label for="identification">Valid ID card or passport No.</label><br />
    <input type="number" id="identification" name="identification"><br /><br />
    <label for="address">Full address of permanent place of residence</label><br />
    <input type="text" id="address" name="address"><br /><br />
    <label for="email">Email address and method of reply.</label><br />
    <input type="email" id="email" name="email"><br /><br />
    <label for="shortdesc">Short description of incident.</label><br/>
    <input type="text" id="shortdesc" name="shortdesc"><br/><br/>
    <label for="incident">Description of Incident.</label><br />
    <textarea id="incident" name="incident"  rows="6" cols="50"></textarea><br /><br />
    <label for="uploaded_file">Select A File To Upload:</label><br />
    <input type="file" id="uploadedFile" name="uploadedFile"><br /><br />    
    <input type="submit" value="Submit" id="complaintSubmit">
</form>

Ajax/Javascript:

submitHandler: function(form) {
    // removes default submit events and establishes AJAX call
    event.preventDefault();
    var brand = faqApp.vars.brand;
    // show loading bars
    $("#callmeback_confirmation").css(cmbEnableCSS).html('<div class="sp sp-circle"></div>').show();
    //var form = ($("#complaintForm")[0]);
    var form = document.getElementById("complaintForm");
    var formMessages = $('#callmeback_confirmation');

    //Getting Files Collection
    var file = $("#uploadedFile")[0].files;

    var formData = new FormData();
    formData.append("mail_id", $('#identification').val());
    formData.append("mail_name", $('#fname').val());
    formData.append("mail_address", $('#address').val());
    formData.append("mail_dob", $('#DOB').val());
    formData.append("cmb_email", $('#email').val());
    formData.append("mail_subject", $('#shortdesc').val());
    formData.append("mail_message", $('#incident').val());
    formData.append("isComplaintForm", $('#isComplaintForm').val());
    formData.append("attachment", $("input[type=file]")[0].files[0]);

    for (var pair of formData.entries()) {
      console.log(pair[0] + ', ' + pair[1]);
    }

    //var object = {};
    //formData.forEach(function(value, key) {
      //object[key] = value;
    //});
    //var fd = JSON.stringify(object);

    //console.log(fd);

    $.ajax({
        type: 'POST',
        timeout: 15000,
        url: faqApp.vars.host + '/cmb.php',
        global: false,
        //dataType: 'json'
        // brand and lang are defined within the code, I had no issue with them before I started working on including an attachment within the complaint form
        data: {
          brand: faqApp.vars.brand,
          lang: faqApp.vars.language,
          formData: formData
        },
        processData: false, // tell jQuery not to process the data
        contentType: false,
        cache: false

php:

$brands = array("abc = abc.com");

$form = $_POST['fd']; // form data stored as array
$brandLang = strtoupper($_POST['brand']."-".$_POST['lang']);
$lang = $_POST['lang'];
//playground
$formFD = $_POST['fd'];

echo "Vardumps ";
echo "</br> $_POST";
var_dump($_POST['fd']);
var_dump($_POST['formData']);
echo "</br> $_FILES";
var_dump($_FILES);
echo "</br>";
print_r($_POST);

if(isset($_POST)){
    echo "Post is set";
    var_dump($_POST);
    var_dump($_FILES);
    } else{
        echo "Post is not set";
    }

Output:

//console.log for loop in formData outputs the following
mail_id, 213123
mail_name, bob ross
mail_address, bob's house
mail_dob, 1111-11-11
cmb_email, bob@gmail.com
mail_subject, bob subject
mail_message, desc
isComplaintForm, 1
attachment, [object File]
//var fd = JSON.stringify(object) prints the following
{"mail_id":"213123","mail_name":"bob ross","mail_address":"bob's house","mail_dob":"1111-11-11","cmb_email":"bob@gmail.com","mail_subject":"bob subject","mail_message":"desc","isComplaintForm":"1","attachment":{}}

The var_dumps basically output nothing, these are the notices shown for the php file:

Notice: Undefined index: fd
Notice: Undefined index: brand 
Notice: Undefined index: lang
Notice: Undefined index: lang
Notice: Undefined index: fd
Vardumps
Array
Notice: Undefined index: fd
NULL
Notice: Undefined index: formData
NULL
Arrayarray(0) { }
Array ( ) Post is setarray(0) { } array(0) { }

The final scope of this is to be able to send an email with an attachment using $_FILES for the file, and $_POST for the text data. But first I need to figure out why $_POST is not containing fd or formData. PS: Im not sure if var fd = JSON.stringify(object); is necessary or not for this scenario.

Any help would be greatly appreciated as I have been stuck on this for a while now.

Also, ‘Request Payload’ is returning [object Object]

Advertisement

Answer

The FormData object has to be the value of the data: option, it can’t be nested inside another object.

submitHandler: function(form) {
    // removes default submit events and establishes AJAX call
    event.preventDefault();
    var brand = faqApp.vars.brand;
    // show loading bars
    $("#callmeback_confirmation").css(cmbEnableCSS).html('<div class="sp sp-circle"></div>').show();
    //var form = ($("#complaintForm")[0]);
    var form = document.getElementById("complaintForm");
    var formMessages = $('#callmeback_confirmation');

    //Getting Files Collection
    var file = $("#uploadedFile")[0].files;

    var formData = new FormData();
    formData.append("mail_id", $('#identification').val());
    formData.append("mail_name", $('#fname').val());
    formData.append("mail_address", $('#address').val());
    formData.append("mail_dob", $('#DOB').val());
    formData.append("cmb_email", $('#email').val());
    formData.append("mail_subject", $('#shortdesc').val());
    formData.append("mail_message", $('#incident').val());
    formData.append("isComplaintForm", $('#isComplaintForm').val());
    formData.append("attachment", $("input[type=file]")[0].files[0]);
    formData.append("brand", faqApp.vars.brand);
    formData.append("lang", faqApp.vars.language);

    $.ajax({
        type: 'POST',
        timeout: 15000,
        url: faqApp.vars.host + '/cmb.php',
        global: false,
        //dataType: 'json'
        // brand and lang are defined within the code, I had no issue with them before I started working on including an attachment within the complaint form
        data: formData,
        processData: false, // tell jQuery not to process the data
        contentType: false,
        cache: false
    });
}

Then in PHP you can access the parameters with $_POST['mail_id'], $_POST['brand'], and $_FILES['attachment'].

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement