Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$('#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

>Solution :

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'])) {
        // ....
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading