douxiegan6468
2014-07-22 00:45 阅读 47

JSON回调的“意外的输入结束” - 从echo(只有两个空行)和错误调用中获取任何内容

I've been trying to create a register system for a site that I'm building.

I already got all the registering process functioning, but I'm not able to get a response back from the server if an error occur or not.

The data is being sent to PHP through jQuery ajax, it is being processed precisely but the results of the processing, which is stored in an Indexed Array, are not being sent back - because of what seems to be a bad JSON object.

I've searched a lot about why is this happening but I cant find a proper answer. Why is this happening?

Here's the code:

Data Is caught from the html via Jquery:

var frm= $('#formreg');

frm.submit(function(ev){
    $.ajax({
        type:frm.attr('method'),
        url: frm.attr('action'),
        dataType: 'json',
        data: frm.serialize()
    }).done(function(data){
        console.log(data);
        alert('Success!');
    }).error(function(xhr, status, error){
        console.log(status,error);
    }).complete(function(xhr, status){
        console.log(status);
    });
    ev.preventDefault();
});

Note the debug lines in done, error and complete, this was a suggestion that I saw somewhere that I got the console log:

parsererror SyntaxError {stack: (...), message: "Unexpected end of input"}

This is the php where it is being processed:

<?php

ob_start();
// Valor nulo para as variaveis antes de iniciar
$username = $password = $nome = $email = $codreg = "";
$host = "localhost"; // Nome do Host
$dbuser = "root"; // Mysql username 
$dbpass = ""; // Mysql password 
$db_name = "usuarios"; // Database name 
$tbl_name = "usuarios"; // Table name
$code_tbl = "codigos";
$returnData = array('success' => false);
$errors = array();
$recieved;

mysql_connect("$host", "$dbuser", "$dbpass")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = test_input($_POST["username"]);
    $password = test_input($_POST["password"]);
    $nome = test_input($_POST["nome"]);
    $email = test_input($_POST["email"]);
    $codreg = test_input($_POST["codReg"]);
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    $data = mysql_real_escape_string($data);
    return $data;
}

$sql = "SELECT * FROM $tbl_name WHERE username='$username'";
$result = mysql_query($sql);
if (mysql_num_rows($result) != 0) {
    $errors['username'] = 'Nome de usuário já existente.';
}

$sqlcode = "SELECT * FROM $code_tbl WHERE codigo='$codreg'";
$resultcode = mysql_query($sqlcode);
if (mysql_num_rows($resultcode) == 0) {
    $errors['codigo'] = 'Código de registro não encontrado.';
}
if (!empty($errors)) {
    $returnData['success'] = false;
    $returnData['errors'] = $errors;
} else {
    $returnData['success'] = true;
    $insert = "INSERT INTO $tbl_name (username, senha, nome, email)
            VALUES ('$username', '$password','$nome','$email')";
    mysql_query($insert);
}
header('Content-Type: application/json');
echo json_encode($returnData);

ob_end_clean();

?>

Thanks in advance and sorry if I used some harsh words or anything, I've been stuck in this error for more than a week and deadline is coming! Im getting desperate!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dsnhalq37505 dsnhalq37505 2014-07-22 02:14

    The issue is with your use of the output buffer.

    The method ob_end_clean() discards the contents of the buffer so basically your script is ending without sending anything back out in the response. From the look of your script you could safely not use a buffer at all. Just remove ob_start() from the beginning and ob_end_clean() from the end.

    If there is more to your code where you do actually need to use a buffer, check out ob_get_contents() to get your output before you close the buffer or ob_end_flush() to close the buffer and output its contents in one call.

    点赞 评论 复制链接分享

相关推荐