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 切换TabTip键盘的输入法
  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序