douxiegan6468 2014-07-22 00:45
浏览 52
已采纳

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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作