简体   繁体   English

AJAX表单未提交导致错误

[英]AJAX form not submitting that gives error

I have my AJAX code here 我在这里有我的AJAX代码

$("#add-student").click(function(e) { 
    e.preventDefault(); 
    formData = $("#student-form").serialize(); 
    if (cleanFormInput()) {
        sendTheInfo(formData);
    } else { 
        shakeForm();
    }
});

function sendTheInfo(formData) { 
    $.ajax({ 
        type: "POST", 
        url: "../classes/ajax/postNewStudent.php",
        data: formData, 
        statusCode: {
            404: function() {
                alert( "page not found" );
            }
        },
        success: function(formData) { 
            console.log("New student submitted:\n" + formData);
        //clearForms();
        },
        error: function(result, sts, err) { 
            console.warn("Connection error:\n" + err + " : " + sts);
            console.log(result);
            shakeForm();
        },
        complete: function() { 
            console.log("Everything complete");
        }
    });
}

Always without fail outputs this error: Connection error: SyntaxError: Unexpected end of input : parsererror 始终没有失败会输出此错误: 连接错误:SyntaxError:意外的输入结束:parsererror

But still gives the complete message: Everything complete 但是仍然给出完整的消息: 一切都完成了

Update, PHP code here: 更新,PHP代码在这里:

    require '../../core/init.php';
    require '../../classes/Config.php';

    header('Content-Type: application/json');

    if (!empty($_POST)) {

        $id = $_POST["sid"]; 
        $first = $_POST["first"];
        $last = $_POST["last"]; 
        $fav = "0";

        $sql = "INSERT INTO `students` (`id`, `first`, `last`, `active`) VALUES ('{$id}', '{$first}', '{$last}', '{$fav}')";

        $link = mysql_connect(Config::get('mysql/host'),Config::get('mysql/username'),Config::get('mysql/password')) or die("could not connect");;
        mysql_select_db(Config::get('mysql/db'), $link);

        $result = mysql_query($sql, $link);

        if ($result) {
            header('Content-Type: application/json');
            $student_data = $id . $first . $last . $fav;
            echo json_encode($student_data);
        }
    }

I'm a bit confused, am I doing my ajax set up wrong? 我有点困惑,我的Ajax设置错误吗? Or is it something else in by backend code wrong? 还是后端代码中的其他错误? I'm using MySQL and jQuery 2.0.3 我正在使用MySQL和jQuery 2.0.3

Updated code here: here 更新的代码在这里: 这里

removed my old answer. 删除了我的旧答案。 I don't think it is an ajax/javascript error. 我认为这不是ajax / javascript错误。 it's definitely a PHP error. 绝对是PHP错误。 It's this lines: 这是这行:

$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);

You $student_data is not an array, it's just a string. $ student_data不是数组,而是一个字符串。 You need to pass an array into the json_encode function 您需要将数组传递给json_encode函数

I have had a look at your code. 我看过你的代码。 I saw that from the PHP side you are sending a JSON object. 我从PHP端看到,您正在发送JSON对象。 but you didn't specified the return dataType for the response. 但是您没有为响应指定返回数据类型 Try to add the dataType in the ajax call. 尝试在ajax调用中添加dataType。 Maybe that will solve the problem 也许那会解决问题

function sendTheInfo(formData) { 
$.ajax({ 
    type: "POST", 
    url: "../classes/ajax/postNewStudent.php",
    data: formData, 
    dataType : 'json',
    statusCode: {
        404: function() {
            alert( "page not found" );
        }
    },
    success: function(formData) { 
        console.log("New student submitted:\n" + formData);
    //clearForms();
    },
    error: function(result, sts, err) { 
        console.warn("Connection error:\n" + err + " : " + sts);
        console.log(result);
        shakeForm();
    },
    complete: function() { 
        console.log("Everything complete");
    }
});
}

It should be noted that the Ajax COMPLETE method will fire even if the back end does not return a result. 应该注意的是,即使后端没有返回结果,Ajax COMPLETE方法也会触发。

complete: function() { 
        console.log("Everything complete");
    } 

will thus show the log'ed entry every time an ajax call is 'finished executing', even if the submit failed. 因此,即使ajax调用“完成执行”,即使提交失败,它也会显示日志条目。

I would also suggest NOT having 2 headers or the same declaration (you have one up top, and one in the if(result) call. 我也建议不要有2个标头或相同的声明(您有一个顶部,并且在if(result)调用中有一个。

In a comment thread, you pointed out that you're working on the server but not locally, And thus that implies you have some pathing issues. 在注释线程中,您指出您正在服务器上工作,而不是在本地工作,因此这意味着您存在一些路径问题。 Check your 检查你的

  ../ 

relative path style urls and make sure that you have the same basepoints. 相对路径样式的网址,并确保您拥有相同的基点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM