dosin84644 2012-11-25 22:26
浏览 28
已采纳

如何阻止javascript和php消息出现

In the code below I have two types of validation. I use a javascript validaton which displays the error message for when the user does not select a course form the "Course" drop down menu.

Then I have a php validation where that if it does not contain a row for the result from the query, then it displays a message stating that no assessments are found.

The problem I am having though is that if the user does not select a course from the "Course" drop down menu and they click on the submit button, it displays both the javascript validation and the php validation.

This is incorrect, what should happen is that :

  • if the user has not selected a course, then it should simply show only the javascript validation and not the php validation.

    • if the user has selected a course from the drop down menu and submits the form, but it then cannot find any results from the query, then it should display the php validation.

My question is what do I need to change in the code in order to be able to not show both validation messages at the same time and show only the correct validation messages when they should be shown?

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
", 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条回答 默认 最新

  • duangu1645 2012-11-25 23:31
    关注

    you could replace

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

    by

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

    That way you can prevent php to make a request when there is no need for this, That's if you want to do the validation server side.

    If you want to prevent the form to be submited when submit button is clicked (client side),

    you could replace onsubmit="return validation();" by onclick="validation();" on the submit button. And if the data passes the validation call $("#yourForm").submit().

    EDIT Here you'll find the complete code as requested

    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
    ", 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 "";
        }
    
        ...
    
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。