AJAX POST到PHP JSON错误

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 :)

I found the solution! Instead of posting back to the same page, I was essentially posting back to a refreshed version of the same page. Thus, no data existed in the $_POST. I fixed this by posting to a separate page, setting the content-type there, and then grabbing the results from that page.

I think you're issue is with the use of dataType and what you are actually outputting. The dataType option is to tell jQuery what type of data to expect back. Personally, I'd leave it off, as jQuery can guess this pretty easily.

Second, you are not actually outputting any JSON from your PHP script. An array in PHP is not automatically converted to JSON. You need to convert it. Also, you should tell the browser what to expect using a header. In PHP:

header("Content-Type: application/json");   //so jQuery knows what to expect
echo json_encode( $myArray );
exit;

json_encode()

On a side note, a plus for leaving out dataType is that it gives you more control over the error. Instead of calling JSON.parse (which jQuery does for you with the dataType setting as json), you could check if the string is valid JSON, and if not, display an error to the user.