Skip to content
Advertisement

SyntaxError: Unexpected token ‘o’, “object(Sim”… is not valid JSON

The purpose of the following code is to go through xml file and see if email or login entered by user are taken, and I want to get a JSON response. Here’s my AJAX code:

$.ajax({
            type: 'post',
            dataType: 'json',
            url: 'create_user.php',
            data: $('form').serialize(),
            success: function (response) {
                if(response['error'] === 'login'){
                    alert('This login is taken');
                } else if(response['error'] === 'email') {
                    alert('This email is taken');
                } else {
                    location.href = 'index.php';
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });

And here’s ‘create_user.php’:

for($i = 0;$i < $size;$i++) {
    if($users->user[$i]->login == $_POST['login']) {
        echo json_encode(array('error' => 'login'));
        $failed = true;
        break;
    }
}
for($i = 0;$i < $size;$i++) {
    if($users->user[$i]->email == $_POST['mail']) {
        echo json_encode(array('error' => 'email'));
        $failed = true;
        break;
    }
}
echo json_encode(array('a' => 'b'));
if(!$failed) {
    echo json_encode(array('error' => 'no'));
}

Advertisement

Answer

It seems you have not prevent PHP code from writing multiple JSON data.

In your code you are first checking for duplicate login and if it is true you are sending output data and after that again checking for email if it is also duplicate your output would be like {"error":"login"}{"error":"email"}{"a":"b"} which is obviously not a valid json formate.

try following code

for($i = 0;$i < $size;$i++) {
    if($users->user[$i]->login == $_POST['login']) {
        echo json_encode(array('error' => 'login'));
        $failed = true;
        exit;
    }
}
for($i = 0;$i < $size;$i++) {
    if($users->user[$i]->email == $_POST['mail']) {
        echo json_encode(array('error' => 'email'));
        $failed = true;
        exit;
    }
}

echo json_encode(array('error' => 'no'));
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement