如何阻止javascript和php消息出现

时间:2012-11-25 22:26:10

标签: php javascript

在下面的代码中,我有两种类型的验证。我使用javascript validaton,当用户没有从“课程”下拉菜单中选择课程时,会显示错误消息。

然后我有一个php验证,如果它不包含查询结果的行,那么它会显示一条消息,指出没有找到评估。

我遇到的问题是,如果用户没有从“课程”下拉菜单中选择课程并且他们点击提交按钮,则会显示javascript验证和php验证。

这是不正确的,应该发生的是:

  • 如果用户没有选择课程,那么它应该只显示javascript验证而不是php验证。

    • 如果用户从下拉菜单中选择了一个课程并提交了表单,但它无法从查询中找到任何结果,那么它应该显示php验证。

我的问题是我需要在代码中进行哪些更改才能够同时显示两条验证消息,并且只显示正确的验证消息?

的Javascript

function validation() {

    var isDataValid = true;

    var courseTextO = document.getElementById("coursesDrop");
    var moduleTextO = document.getElementById("modulesDrop");

    var errModuleMsgO = document.getElementById("moduleAlert");

    if (courseTextO.value == "") {
        $('#targetdiv').hide();
        $('#assessmentForm').hide();
        $('#updateForm').hide();
        $('#submitupdatebtn').hide();
        errModuleMsgO.innerHTML = "Please Select a Course";
        isDataValid = false;
    } else {
        errModuleMsgO.innerHTML = "";
    }
    return isDataValid;

}​

PHP / HTML

<?php

// connect to the database
include('connect.php');


/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    die();
}


$sql = "SELECT CourseId, CourseNo, CourseName FROM Course ORDER BY CourseId"; 

$sqlstmt=$mysqli->prepare($sql);

$sqlstmt->execute(); 

$sqlstmt->bind_result($dbCourseId, $dbCourseNo, $dbCourseName);

$courses = array(); // easier if you don't use generic names for data 

$courseHTML = "";  
$courseHTML .= '<select name="courses" id="coursesDrop">' . PHP_EOL; 
$courseHTML .= '<option value="">Please Select</option>' . PHP_EOL;  

$outputcourse = "";

while($sqlstmt->fetch()) 
{

    $course = $dbCourseId;
    $courseno = $dbCourseNo;
    $coursename = $dbCourseName; 

    $courseHTML .= "<option value='" . $course . "'>" . $courseno . " - " . $coursename . "</option>" . PHP_EOL;  

    if (isset($_POST['courses']) && ($_POST['courses'] == $course)) {
        $outputcourse = "<p><strong>Course:</strong> " . $courseno .  " - "  . $coursename . "</p>";
    }

} 

$courseHTML .= '</select>'; 

?>

<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return validation();">
    <table>
        <tr>
            <th>Course: <?php echo $courseHTML; ?></th>
        </tr>
    </table>
    <p>
        <input id="moduleSubmit" type="submit" value="Submit Course and Module" name="moduleSubmit" />
    </p>
    <div id="moduleAlert"></div>
    <div id="targetdiv"></div>
</form>


<?php

if (isset($_POST['moduleSubmit'])) {    

    $sessionquery = "
    SELECT SessionId, SessionName, SessionDate, SessionTime, CourseId, SessionActive
    FROM Session
    WHERE (CourseId = ? AND SessionActive = ?)
    ORDER BY SessionName 
    ";

    $active = 1;

    $sessionqrystmt=$mysqli->prepare($sessionquery);
    // You only need to call bind_param once
    $sessionqrystmt->bind_param("si",$course, $active);
    // get result and assign variables (prefix with db)

    $sessionqrystmt->execute(); 

    $sessionqrystmt->bind_result($dbSessionId,$dbSessionName,$dbSessionDate,$dbSessionTime, $dbCourseId, $dbSessionActive);

    $sessionqrystmt->store_result();

    $sessionnum = $sessionqrystmt->num_rows();   

    if($sessionnum == 0) {
        echo "<p><span style='color: red'>Sorry, You have No Assessments under this Module</span></p>";
    } 
    else 
    { 
        echo "";
    }

    ...

}
?>

1 个答案:

答案 0 :(得分:1)

你可以替换

if (isset($_POST['moduleSubmit']))

通过

if (isset($_POST['coursesDrop']) && $_POST['coursesDrop']!="")

这样你可以阻止php在不需要时发出请求, 那就是你想要验证服务器端。

如果要在单击提交按钮(客户端)时阻止提交表单,

您可以在提交按钮上用onsubmit="return validation();"替换onclick="validation();"。 如果数据通过了验证调用$("#yourForm").submit()

编辑在这里,您可以找到所需的完整代码

JAVASCRIPT

function validation() {

    var isDataValid = true;

    var courseTextO = document.getElementById("coursesDrop");
    var moduleTextO = document.getElementById("modulesDrop");

    var errModuleMsgO = document.getElementById("moduleAlert");

    if (courseTextO.value == "") {
        $('#targetdiv').hide();
        $('#assessmentForm').hide();
        $('#updateForm').hide();
        $('#submitupdatebtn').hide();
        errModuleMsgO.innerHTML = "Please Select a Course";
        isDataValid = false;
    } else {
        errModuleMsgO.innerHTML = "";
    }

    if(isDataValid){
        $("#myForm").submit();
    }

}​

PHP HTML     

// connect to the database
include('connect.php');


/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    die();
}


$sql = "SELECT CourseId, CourseNo, CourseName FROM Course ORDER BY CourseId"; 

$sqlstmt=$mysqli->prepare($sql);

$sqlstmt->execute(); 

$sqlstmt->bind_result($dbCourseId, $dbCourseNo, $dbCourseName);

$courses = array(); // easier if you don't use generic names for data 

$courseHTML = "";  
$courseHTML .= '<select name="courses" id="coursesDrop">' . PHP_EOL; 
$courseHTML .= '<option value="">Please Select</option>' . PHP_EOL;  

$outputcourse = "";

while($sqlstmt->fetch()) 
{

    $course = $dbCourseId;
    $courseno = $dbCourseNo;
    $coursename = $dbCourseName; 

    $courseHTML .= "<option value='" . $course . "'>" . $courseno . " - " . $coursename . "</option>" . PHP_EOL;  

    if (isset($_POST['courses']) && ($_POST['courses'] == $course)) {
        $outputcourse = "<p><strong>Course:</strong> " . $courseno .  " - "  . $coursename . "</p>";
    }

} 

$courseHTML .= '</select>'; 

?>

<form id="myForm" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
    <table>
        <tr>
            <th>Course: <?php echo $courseHTML; ?></th>
        </tr>
    </table>
    <p>
        <input id="moduleSubmit" type="button" value="Submit Course and Module" name="moduleSubmit" onclick="validation();" />
    </p>
    <div id="moduleAlert"></div>
    <div id="targetdiv"></div>
</form>


<?php

if (isset($_POST['moduleSubmit'])) {    

    $sessionquery = "
    SELECT SessionId, SessionName, SessionDate, SessionTime, CourseId, SessionActive
    FROM Session
    WHERE (CourseId = ? AND SessionActive = ?)
    ORDER BY SessionName 
    ";

    $active = 1;

    $sessionqrystmt=$mysqli->prepare($sessionquery);
    // You only need to call bind_param once
    $sessionqrystmt->bind_param("si",$course, $active);
    // get result and assign variables (prefix with db)

    $sessionqrystmt->execute(); 

    $sessionqrystmt->bind_result($dbSessionId,$dbSessionName,$dbSessionDate,$dbSessionTime, $dbCourseId, $dbSessionActive);

    $sessionqrystmt->store_result();

    $sessionnum = $sessionqrystmt->num_rows();   

    if($sessionnum == 0) {
        echo "<p><span style='color: red'>Sorry, You have No Assessments under this Module</span></p>";
    } 
    else 
    { 
        echo "";
    }

    ...

}
?>