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?

asked Sep 5, 2014 at 14:35
\$\endgroup\$

2 Answers 2

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.
answered Sep 6, 2014 at 14:43
\$\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

answered Sep 6, 2014 at 7:42
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.