3
<?PHP
//$errorMessage = "";
//$check = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
        //===================================================
        //  GET THE QUESTION AND ANSWERS FROM THE FORM
        //===================================================
    $sID = $_POST['studentID'];
    $sID  = htmlspecialchars($sID);
        $firstName = $_POST['firstName'];
        $firstName  = htmlspecialchars($firstName);
        $lastName = $_POST['lastName'];
        $lastName  = htmlspecialchars($lastName);
        $grade = $_POST['grade'];
        $grade  = htmlspecialchars($grade);
        //var_dump($grade);

        //============================================
        //  OPEN A CONNECTION TO THE DATABASE
        //============================================
    $user_name = "root";
    $password = "";
    $database = "surveyTest";
    $server = "127.0.0.1";
    $db_handle = mysql_connect($server, $user_name, $password);
    $db_found = mysql_select_db($database, $db_handle);
    if ($db_found) {
        //============================================
        //  GET THE LAST QUESTION NUMBER
        //============================================
            $SQL = "Select * FROM students WHERE SID='$sID'";
            $result = mysql_query($SQL);
            $db_field = mysql_fetch_assoc($result);
            $studentID = $db_field['SID'];
            var_dump($studentID);
            //=========================================================
            //  Add a student to the students TABLE
            //=========================================================
            $SQL = "INSERT INTO students (SID, fName, lName, Grade) VALUES ('$sID', '$firstName', '$lastName', '$grade')";
            $result = mysql_query($SQL);
            //=============================================================
           //   SET Multiple rows IN THE answers TABLE for each question for a given student.
           //=============================================================
            /*$SQL = "Select * FROM tblquestions";
            $result = mysql_query($SQL);
            $numRows = mysql_num_rows($result); //return number of rows in the table
            for ($i = 1; $i <= $numRows; $i++){
                $qNum = 'q1';
                $SQL = "INSERT INTO answers (QID, A, B, C, D, E, SID) VALUES ('$qNum', 0, 0, 0, 0, 0, '$sID')";
                $question_Number = ltrim($qNum,'q');
                $question_Number++;
                $qNum ='q'.$question_Number;
                $result = mysql_query($SQL);
            }*/
            mysql_close($db_handle);
            print "The student with the following ID ".$sID. " has been added to the database";
        }
    else {
        print "Database NOT Found ";
        mysql_close($db_handle);
    }

}
?>
<html>
<head>
<title>Survey Admin Page</title>
</head>
<body>

<FORM NAME ="setQuestionForm" METHOD ="POST" ACTION ="setStudent.php" id="sStudent">
            <p>Enter student ID: <INPUT TYPE = 'TEXT' Name ='studentID' size="4"></p>
            <p>Enter First Name: <input type="text" name="firstName" size="20"></p>
            <p>Enter Last Name: <input type="text" name="lastName" size="20"></p>
            <p>Select Grade: <select name = "grade">
                <option value = "1">First Grade</option>
                <option value = "2">Second Grade</option>
                <option value = "3">Third Grade</option>
                <option value = "4">Fourth Grade</option>
                <option value = "5">Fifth Grade</option>
                <option value = "6">Sixth Grade</option>
                <option value = "7">Seventh Grade</option>
                <option value = "8">Eighth Grade</option>                           
            </select></p>
            <INPUT TYPE = "submit" Name = "Submit1"  VALUE = "Add Student">
        </FORM>
    <P>



<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
    $(function(){
        if ($('form').length > 0) {
            $('form').submit(function(e){
                var check = "<?php echo $studentID; ?>";
                alert(check);
                if (check != "")
                {
                    alert ("This user already exists");
                    return false;
                }
                else
                {
                    return true;
                }
            });   
        } 
    }) 
</script>
</body>
</html>

上面的代码用于将学生添加到数据库中,我正在尝试进行一些表单验证以避免重复记录。我的问题是我设置了一个 php 变量 $studentID 来验证数据库是否包含具有相同 ID 的学生。

但是,当我尝试添加重复记录时,似乎我的 javascript 代码首先执行,这可以通过 JQuery 代码中的警报消息观察到,它显示一个空字符串框。再次执行代码,做正确的事。

关于如何解决这个问题的任何帮助?

4

1 回答 1

5

在初始页面加载时:流程如下所示:

服务器端代码 -> 向客户端发送数据 -> 浏览器开始渲染和执行 JS

在表单上提交:

客户端执行代码(javascript)-> 向服务器发送数据-> 服务器获取数据和进程

要更改其工作方式,您需要执行ajax发布表单提交并在“成功”时执行上述 JavaScript。您可以发布到同一页面或将其更改为 RESTful 服务。

以下是来自 jQuery 的 AJAX 和 POST 函数的示例:

AJAX

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

发布(JS)

$.post('ajax/test.html', function(data) {
  $('.result').html(data);
});

这是专门为您准备的结果,采用上面的两个片段。

JavaScript/jQuery

$(function () {
    if ($('form').length > 0) {
        $('form').submit(function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "YOUR-URL",
                data: YOUR - FORM - DATA,
                success: function (result) {
                    //result will contain the xml or JSON result of calling the FORM
                    var check = "<?php echo $studentID; ?>";
                    alert(check);
                    if (check != "") {
                        alert("This user already exists");
                        return false;
                    } else {
                        return true;
                    }
                },
                dataType: "XML-OR-JSON"
            });
        });
    }
})
于 2013-07-08T17:37:04.667 回答