AJAX表单执行PHP脚本但返回错误

时间:2012-10-25 05:55:29

标签: php jquery ajax json

我的PHP脚本正在成功执行,表单中的记录被插入到数据库中,但是,每次按“提交表单按钮”时,它都会向我发出警告“错误”,因此我的成功函数没有被执行,我不知道为什么。

JAVASCRIPT

$(document).ready(function () {
    $(".button").click(function () {
        var dataString = 'name=' + name + '&email=' + email + '&comment=' + comment;
        $.ajax({
            type: 'POST',
            url: 'submit_form.php',
            dataType: 'json',

            data: dataString,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('error');
                $('#message').removeClass().addClass('error')
                    .text('There was an error.').show(500);
            },
            success: function (data) {
                $('#contact_form').html("<div id='message'></div>");
                $('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
                    .text(data.msg).show(500);
                $('#contact_form').hide();
            }
        });
        return false;
    });
});

PHP

//mysql connection string // 
$result = $mysqli->query("**fetch # of rows**");
$count  = $result->fetch_object()->Total;
$result->free();

echo "number of rows is $count";

if ($count > 10) {
    $return['error'] = true;
    $return['msg']   = 'Sorry The Queue is full';
}elseif ($stmt = $mysqli->prepare("**insert into db**")) {
    /* Bind our params */
    $stmt->bind_param("sss", $param1, $param2, $param3);

    /* Set our params */
    $param1 = $_POST["param1"];
    $param2 = $_POST["param2"];
    $param3 = $_POST["param3"];

    /* Execute the prepared Statement */
    $stmt->execute();
    $return['error'] = false;
    $return['msg']   = 'Thanks your comment was added!';

    /* Close the statement */
    $stmt->close();
} else {
    /* Error */
    printf("Prepared Statement Error: %s\n", $mysqli->error);
}

echo json_encode($return);

1 个答案:

答案 0 :(得分:5)

该行:

echo "number of rows is $count";

将导致无效的JSON。