2
\$\begingroup\$

I'm looking to collect form input and pass it to a file called processing.php with AJAX

JS:

$(document).ready(function () {

    var serializedSubmission;
    var responseObj;

    $('#myForm').on('submit', function (e) {
        e.preventDefault();
        serializedSubmission = $('#myForm').serialize(); // get input
        if (checkInput()) { // validate
            process();  // append 'action' and process data
        }

    });

    /* data processing functions */
    // verify all parameters have values
    function checkInput() {
        var temp = decodeURIComponent(serializedSubmission);
        if (temp.search('=&') > 0 || temp.slice(-1) == '=') {
            console.log('Form is missing parameters!');
            return false;
        } else {
            return true;
        }
    }

    // append 'action' and pass data to php
    function process() {
        var data = {'action': 'demo'}; // set action to correspond with processing.php
        data = serializedSubmission + "&" + $.param(data);
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'php/processing.php',
            data: data,
            success: function (data) {
                responseObj = JSON.parse(data['json']);
                console.log('ajax success:');
                console.log(responseObj);
            },
            error: function (xhr, desc, err) {
                console.log(xhr);
                console.log('Details: ' + desc + '\nError: ' + err);
            }
        });
    }
});

PHP:

<?php
if(isAjax()) {
    if(isset($_POST['action']) && !empty($_POST['action'])) { // check if action value exists
        $action = $_POST['action'];
        switch($action) {
            case 'demo':
                demo();
                break;
        }
    }
}

// check if ajax request
function isAjax() {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower(
        $_SERVER['HTTP_X_REQUESTED_WITH']
    ) == 'xmlhttprequest';
}


// action = 'demo'
function demo() {
    $return = $_POST;
    $return['json'] = json_encode($return);
    echo json_encode($return);
}

// action = 'widget'
function widget() {
    // do stuff
    echo json_encode($return);
}

How's it look?

\$\endgroup\$
3
\$\begingroup\$

On client-side, some small points ...

  1. Avoid more $(selector) phrases than absolutely necessary. Inside the submit handler, you can use $(this), which will be faster.
  2. Pass serializedSubmission formally to the subroutines rather than rely on an outer var.
  3. The outer var responseObjcan't be reliably used except in an asynchronous context, so if you want to cache anything, cache the promise returned by $.ajax(), not the data.
  4. Needs less obvious comments and more on things that matter, eg against lines like if (temp.search('=&') > 0 || temp.slice(-1) == '='), which I had to study to work out the validation strategy. Maybe a few words would have helped me.
\$\endgroup\$
1
\$\begingroup\$

Overall looks fine, only a couple of picky little things

// you don't need to test for isset and empty
if(isset($_POST['action']) && !empty($_POST['action'])) { // check if action value exists

// this test will achieve the same, one of the quirky things about empty function is 
// that is doesn't throw an error if the index doesn't exist
if(!empty($_POST['action'])) { // check if action value exists

When returning json data from php, it is best to set a php header to indicate that.

$return = $_POST;
$return['json'] = json_encode($return);
header('Content-Type: application/json');
echo json_encode($return);

Is it intentional to encode $return, then encode it again when you echo?, seems a little unusual to me. If you just do json encoding when you echo, you won't need to parsejson in your js

Depending on what version of jquery you are using, this may or may not be relevant

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

$.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'php/processing.php',
            data: data
})
  .done(function (data) {
     responseObj = JSON.parse(data['json']);
     console.log('ajax success:');
     console.log(responseObj);
 },
 .fail(function (jqXHR, textStatus) {
    console.log(xhr);
    console.log('Details: ' + textStatus);
    }
});

Also be careful with the use of console in production code, it doesn't work in all versions of internet explorer. https://stackoverflow.com/questions/3326650/console-is-undefined-error-for-internet-explorer

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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