jquery - Form $_POST Variables empty in PHP Handler
I've converted a working form to use Bootstrap's StepWizard and now when the form is submitted via the same Ajax method as with the previous form the PHP handler says all variables are null.
Ajax call:
// Put the form data into a serialized string and make Ajax call
var formData = $("#entryForm").serialize();
console.log(formData);
$.ajax({
method: "POST",
url: "/contest/entry/php/formSubmit_TAB_WIZ.php",
data: formData,
global: true, // SHOW MODAL FOR THIS AJAX REQUEST VIA AJAX START/STOP
success: function (result){
// console.log('in success function; result=' + result);
// if (result === 'SUCCESS') {
// location.href = "/contest/entry/php/printout_TAB_WIZ.php";
location.href = "/contest/entry/php/formSubmit_TAB_WIZ.php";
// } else {
// //alert(result);
// jqUIAlert(result, false);
// }
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log('In error function; jqXHR=' + jqXHR.status);
//console.log('In error function; textStatus=' + textStatus);
//console.log('In error function; errorThrown=' + errorThrown);
//alert('Error processing Ajax request (formSubmit): ' + jqXHR.status + ' ' + errorThrown);
jqUIAlert('Error processing Ajax request (formSubmit): ' + jqXHR.status + ' ' + errorThrown, false);
},
complete: function (jqXHR, textStatus) {
$("input[type=submit]").removeAttr("disabled");
$("input[type=submit]").val('Submit');
}
});
The console shows the serialized data just fine (I added line breaks after each parameter for clarity):
token=aa5077b808388b52050aba342f11a7c3fd4c9d37ebe9f7e94425edeaf1b20920
&fName=Ross
&lName=Waddell
&phone=555%20555%201212
&email=a%40b.com
&modelName=
&remarks=
&category=
&securedToBase=Yes
&acceptAgrmt=
&g-recaptcha-response=03AGdBq25_SV2ouAUrzAs_QsbEVZcmJUGEXrQXmRYBSQbZhtoyTKwI0xmIodkozOt0l9jntAqqwaJH-QqYWJj_tF127jDbi00XBVv9AGa2nX5wZRf_uj8RuosO7NnGP4i6BiiFi5lPmgau6we_9gKu84QHpFQ-tlB_HtYNouPWtDgyjCeasIo1noqbjfBZz1BsSWhmyCPHDoq9A4P1u_cYWtY67U9jFSFhEimHVNakdpsnnPsSqDW8Uf9puLnZG5EjuKm5RV5kdaNMPH64DGpmJTnQzepz6G2T56_CASy1mYstOmBvSv22p3ZpmY2hUMPkVR_2WdixAdBb_JwQtgyfA6zrfG9FJLo7aQ4gHwQd8n5Zh1M5XMH9HDusrAlopNcPfLtCGyg573T5CwJtTr0wzQuguvlftCL-bT8uDTcpQzj8ZqtV2-XMc5GFDwpeRB2vJKyX2DcIbVHa
But my PHP handler throws errors (this is just for one of the $_POST variables):
PHP Notice: Undefined index: fName in /public_html/contest/entry/php/formSubmit_TAB_WIZ.php on line 35
PHP Handler (formSubmit_TAB_WIZ.php):
<?php
// include setConfig
require_once '../../../../private/contest/include/setConfig.php';
// include startSession
require_once '../../../../private/contest/include/startSession.php';
startWFsession('entry_form');
$sessionToken = isset($_SESSION['token']) ? bin2hex($_SESSION['token']) : '';
$log->debug('formSubmit.php: starting/loading session',
array('file:' => basename(__FILE__),
'line#:' => __LINE__,
'session_id' => session_id(),
'$_SESSION["token"]' => $sessionToken));
$_SESSION['current_time'] = time();
// print_r($_POST);
// $post_data = file_get_contents('php://input');
// echo $post_data;
$ip = getUserIP();
$sessionID = session_id();
$log->debug('POST variables from new TAB WIZARD form:',
array('file:' => basename(__FILE__),
'line#:' => __LINE__,
'session_id' => $sessionID,
'IP' => $ip,
'$_POST["token"]' => $_POST["token"],
'$_POST["fName"]' => $_POST["fName"],
'$_POST["lName"]' => $_POST["lName"],
'$_POST["phone"]' => $_POST["phone"],
'$_POST["email"]' => $_POST["email"],
'$_POST["modelEntryList"]' => $_POST["modelEntryList"]
));
die();
What's baffling is the old form still works just fine, using the same Ajax call and similar PHP code (so I know this isn't a case of PHP.ini property values). I've run the new form through an HTML validator and all checks out - all the form names are unique and it is serializing properly.
I've tried to debug this for days with no luck - can someone point me in the right direction?
EDIT The HTML for my form submit button:
<input type="submit" id="formsubmit" name="mysubmit" class="btn btn-danger pull-right" value="Submit">
JS Code to prevent default submission:
$("#entryForm").on("submit", function(e) {
// Triggered by form submission: do all field validations
//console.log('In $("#entryForm").on("submit", function() ...');
// Disallow browser form submission
e.preventDefault();
var oForm = document.forms["entryForm"];
//var oForm = $('form[name="entryForm"]'); Easier to use pure JS here
// User has to check Terms and Conditions for new entry
if(!oForm.elements["acceptAgrmt"].checked) {
oForm.elements["acceptAgrmt"].focus();
//alert("Please accept the Terms and Conditions.");
jqUIAlert("Please accept the Terms and Conditions.", false);
return false;
}
if (validateForm(oForm)) {
//console.log('Validation succeeded.');
// Validation succeeded, so now explicitly call reCAPTCHA check
grecaptcha.execute();
} else {
//console.log('Validation failed; preventing form submission');
return false;
}
});
EDIT2 Looking at the network traffic in Chrome's developer tools I see to lines for my PHP handler (formSubmit_TAB_WIZ.php) but only one looks like a POST when I filter by 'method:POST'. But no matter what I do in terms of how I invoke the Ajax call, I see two records in my PHP logger: the first one has all the input values, and the second has all null. What the what is going on here?
EDIT3 Looks like the 2nd request is a GET - but why?
192.168.1.18 - - [05/Jan/2021:20:28:16 -0500] "POST /contest/entry/php/formSubmit_TAB_WIZ.php HTTP/1.1" 200 1907 "http://wonderfest:8000/contest/entry/entryForm_TAB_WIZ_v4.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
192.168.1.18 - - [05/Jan/2021:20:28:16 -0500] "GET /contest/entry/php/formSubmit_TAB_WIZ.php HTTP/1.1" 200 238 "http://wonderfest:8000/contest/entry/entryForm_TAB_WIZ_v4.php" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
Answer
Solution:
The GET is coming from the redirect in the Ajax success function:
$.ajax({
method: "POST",
url: "/contest/entry/php/formSubmit_TAB_WIZ.php",
data: formData,
global: true, // SHOW MODAL FOR THIS AJAX REQUEST VIA AJAX START/STOP
success: function (result){
console.log('in success function; result=' + result);
if (result === 'SUCCESS') {
location.href = "/contest/entry/php/formSubmit_TAB_WIZ.php";
} else {
//alert(result);
jqUIAlert(result, false);
}
},
error: function (jqXHR, textStatus, errorThrown) {
jqUIAlert('Error processing Ajax request (formSubmit): ' + jqXHR.status + ' ' + errorThrown, false);
},
complete: function (jqXHR, textStatus) {
$("input[type=submit]").removeAttr("disabled");
$("input[type=submit]").val('Submit');
}
});
I wanted to see the variable values on the page, so I used the same PHP handler here but of course that turns into a GET. So, the first request was actually working fine, but the errors in my php_error.log were from the 2nd GET request since naturally the $_POST variables were null.
Source