在Javascript之前首先执行PhP代码 [英] Making PhP code executes first before Javascript

查看:88
本文介绍了在Javascript之前首先执行PhP代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?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的学生。

The above code is used to add students to a database, and I'm trying to do some form validation to avoid duplicated records. My problem is that I set a php variable $studentID that verifies whether the database contain the a student with the same ID.

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

However, when I try to add a duplicated record, it seems like my javascript code executes first and this can be observed by the alert message in the JQuery code that it shows a box of an empty string. Executing the code once more, do the correct thing.

我可以解决这个问题的任何帮助吗?

Any help of how I can fix this?

推荐答案

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

On initial page load: The process flow looks like this:


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

Server Side code -> sends data to client -> browser begins rendering and executing JS

在表单上提交:


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

Client Executes code (javascript) -> Sends data to server -> Server gets data and processes

改变你的工作方式,你想做一个 ajax 发布表单提交和成功,然后执行上述JavaScript。您可以发布到同一页面或将其更改为RESTful服务。

to change the way this works you would want to do an ajax or post form submit and on "success" then execute the above JavaScript. You can post to the same page or change it to a RESTful service.

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

Here are examples of AJAX and POST functions from jQuery:

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



POST(JS)



POST (JS)

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






以下是专门针对您的结果,取两个片段。

$(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"
            });
        });
    }
})

这篇关于在Javascript之前首先执行PhP代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆