Skip to content
Advertisement

AJAX POST submit to PHP – empty POST on arrival at PHP?

I am submitting a POST request via AJAX to my PHP script. The browser tools Network tab shows the POST data has values, on arrival at my PHP script the $_POST value is true, isset() verification is valid, and there should be no problem to assign the $_POST['input'] values to my $variables.

Yet, my debug bar tells me that the PHP variables like $first_name are infact empty. I am feeling very stupid here, what am I missing?

AJAX

$('#newUserSubmit').click(function() {
    console.log('Submit button clicked.');

    if ($('#addNewUser').valid()) {
        console.log('Form on submit is valid');

        $.ajax({
            type: 'POST',
            url: '../../controllers/admin_addNewUser.php',
            data: {
                action: 'add_new_user',
                user_data: $('#addNewUser').serialize()
            },
            cache: false,
            success: function(data) {
                alert(data);
                console.log('Ajax POST request successful.');
            },
            error: function(xhr, status, error) {
                console.log('Ajax POST request failed.');
                console.error(xhr);
            }
        });

    } else {
        console.log('Form on submit is invalid');
        return false;
    }
});

Browser Network Tab:

Request Data
MIME Type: application/x-www-form-urlencoded; charset=UTF-8
action: add_new_user
user_data: first_name=John&last_name=Doe

PHP

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $debug_msg = 'POST check: passed<br>';

    if (isset($_POST['action']) && ($_POST['action'] == 'add_new_user')) {
        $debug_msg .= 'ISSET check: passed<br>';

        // sanitize
        $fn = mysqli_real_escape_string($db, $_POST['first_name']);
        $ln = mysqli_real_escape_string($db, $_POST['last_name']);

    }
}

Response:

<b>Notice</b>:  Undefined index: first_name in <b>/path/to/script/admin_addNewUser.php</b> on line <b>27</b><br />
<br />
<b>Notice</b>:  Undefined index: last_name in <b>/path/to/script/admin_addNewUser.php</b> on line <b>28</b><br />

Appreciate any help on this, been staring at this for too long already. Thanks

Advertisement

Answer

you are sending the data object wrong. Sending the Serialize function as an object element will send it literally as a string. so the output for your data obj will be something like

data: {
    "action": "add_new_user",
    "user_data": "first_name=val&last_name=anotherval"
}

wich will be parsed as an array on the PHP side.

So you will need to replace the

data: {
    action: 'add_new_user',
    user_data: $('#addNewUser').serialize()
}

by something like:

data: $('#addNewUser').serialize() + '&action=add_new_user'

OR in PHP side you will need to parse the user_data query string into an array like the following:

if (isset($_POST['user_data'])) {
    parse_str($_POST['user_data'], $userData);

    // then you can 
    if (isset($userData['first_name'])) {
        // ....
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement