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?