First, I know there's a lot of very similar posts on StackOverflow. I've looked through them all, and still been unable to solve this problem.
I've got a form that a user fills out, and due to very strict JavaScript validation (which must remain in place), the user is likely to have to return to the form after a failure or two. Submission of the form triggers a JavaScript function that does validation, before using AJAX to POST the data to PHP.
Essentially, this is all happening on one page. There is a hidden div on the page that is loaded through jQuery once the AJAX request goes off, meanwhile, the form itself is subsequently hidden. The page sets PHP variables based off of the data received from the AJAX POST (through $_POST), and sends this information off to an API through cURL.
I'm debugging the 'formData' object before POSTing it with AJAX, and it is successfully capturing my information, and appears to be a valid object.
The AJAX POST itself is successful when using dataType: 'text'. However, I need dataType: 'json'. Immediately after adding dataType: 'json' to my AJAX POST, it returns the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
My code is as follows:
JAVASCRIPT / AJAX / JQUERY:
formData = {
"fname": $('#fname').val(),
"middle": $('#middle').val(),
"lname": $('#lname').val(),
"sex": gender,
"email": $('#email').val(),
"address1": $('#address1').val(),
"city": $('#city').val(),
"state": $('#state').val(),
"zip": $('#zip').val(),
"phone": $('#phone').val(),
"altphone": $('#altphone').val(),
"email": $('#email').val(),
"year": $('#year').val(),
"month": $('#month').val(),
"day": $('#day').val(),
"pass": $('#pass').val(),
"pin": $('#pin1').val() + $('#pin2').val() + $('#pin3').val() + $('#pin4').val(),
"ssn": $('#ssn1').val() + $('#ssn2').val() + $('#ssn3').val(),
"username": $('#username').val()
}
console.debug(formData);
// AJAX POST to the same page
$.ajax({
type: "POST",
url: 'index.php',
data: formData,
dataType: 'json',
success: function (data, textStatus, jqXHR) {
// Switch divs
$('#submit').addClass('visible');
$('#form').addClass('invisible');
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ': ' + errorThrown);
}
});
PHP code inside #submit:
session_start();
// Variables
$fname = $_POST['fname'];
...
// Testing
var_dump($_POST);
echo "<br /><br />";
var_dump($_GET);
echo "<br /><br />";
var_dump($_REQUEST);
// cURL Stuff
$_POST, $_GET and $_REQUEST all return empty arrays when using dataType: 'text', though I'm pretty sure that the $_POST will come through correctly once the JSON is fixed up.
I can't for the life of me see what is wrong with the JSON syntax, but it may have to do with the automatic formatting AJAX is applying.
Hopefully this is a trivial error that someone can spot easily! Any help tracking it down would be greatly appreciated :)