проверка модальной формы начальной загрузки и модальных нагрузок после загрузки DOM - PullRequest
0 голосов
/ 25 сентября 2018

перед основным вопросом я хотел бы описать структуру файлов моего сайта для лучшего обзора.У меня есть много страниц на моем веб-сайте, которые динамически добавляются через мой index.php. Вот код index.php

    <?php
include ('pages/tillBody.php');
include ('pages/navbar.php');
// Set the default name 
$ac = 'default.php'; 
// Specify some disallowed paths 
$disallowed_paths = array('tillBody', 'navbar', 'footer');
if(empty($_GET['ac'])){
$_SESSION["loggedin"] = false;
unset ($_SESSION['userstatus']);
unset ($_SESSION['loggedin']);
unset ($_SESSION["userfn"]);
unset ($_SESSION["userln"]);
unset ($_SESSION["useremail"]);
unset ($_SESSION["id"]);
session_unset();
session_destroy();
}
if (!empty($_GET['ac'])) {
    $q = basename($_GET['ac']); 
    // If it's not a disallowed path, and if the file exists, update $action
    if (!in_array($q, $disallowed_paths) && file_exists("pages/{$q}.php"))
    {
        $ac = $q.".php";
    }
}
// Include $action 
include("pages/$ac"); 

include("pages/footer.php");
?>

в моей папке страниц, у меня есть более 150 страниц, и на некоторых страницах есть кнопки, которые запускают загрузчикМодальности 3.3.7, и на той же странице у меня есть половина кода, остающийся модальным кодом, взятый со страницы php, который я собираюсь показать вам позже, это код одной из моих страниц, который содержит кнопку и половину кода модального.

    <!--button for modal-->
        <button id="<?php if($row['id'] != NULL || trim($row['id']) !=''){echo $row['id'];}?>" type="button" class="btn-verified complaintId" style="color:#000; background: none; border: none;" data-toggle="complaintmodal"> Report</button>
    <!--compalaint modal start-->
    <div class="modal fade" id="complaintModal" role="dialog" data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog modal-lg">
           <div class="modal-content">
             <div class="cbgoverlay">
             </div>
           </div>
        </div>
   </div>
   <!--compalaint modal ends-->

Когда пользователь нажимает кнопку, он запускает модал, и в то же время я запускаю свою функцию jquery, чтобы загрузить оставшееся содержимое модала через ajax.В моем файле custom.js у меня есть этот код.

$('.complaintId').on('click',function(){
    complaintid=(this.id);
    $.ajax({
        method: 'POST',
        url: 'complaintmodalshow.php',
        data: {id:complaintid},
        success: function(data){
            $(".cbgoverlay").html(data);
            $('#complaintModal').modal({
                show:true
            });
        }
    });
});

отсюда я загружаю оставшийся модальный код модала, потому что мне нужно заполнить его из базы данных, и вот код complaintmodalshow.php

<?php
if(!empty($_POST['id'])){
    $id = $_POST['id'];
    // connection to the Ddatabase
    $servername = "*******";
    $username = "*************";
    try {
    $db = new PDO("mysql:host=$servername;dbname=*********", $username, "***********");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $id = trim($id);
    $id = stripslashes($id);
    $id = htmlspecialchars($id);
    $id = (int)$id;
    $query = "SELECT dou.businessName, dou.businessAddress, wp.discount, wp.dealitem, wp.expirydate, 
    wp.description, m.* FROM dineOwnerUser AS dou INNER JOIN webpromo AS wp ON dou.id = wp.ownerid 
    INNER JOIN menu AS m ON dou.id = m.ownerid
    WHERE dou.id = ?";

    $statement = $db->prepare($query);
    $statement->execute(array($id));
    $result = $statement->fetch(PDO::FETCH_ASSOC);
    echo"<div class='modal-header'>";
    echo"<button type='button' class='close' data-dismiss='modal'>&times;</button>";
    echo"<h2 class='modal-title text-center' style='color:#8f0000d6'>Report to ".$result['businessAddress']."</h2>";
    echo"</div>";
    echo"<div class='modal-body'>";
    echo"<form id='complaintForm'>";
        echo"<div class='form-group'>";
            echo"<label class='control-label' for='complaintAbout'>Report / Complaint about* :</label>";
            echo"<input type='text' class='form-control' id='complaintAbout' placeholder='Report / Complaint about' name='complaintAbout'>";
            echo"<div class='alert alert-danger hidden' id='complaintAbouterrbox'></div>";
        echo"</div>";
        echo"<div class='form-group'>";
            echo"<label class='control-label' for='complaintDetail'>Report / Complaint detail* :</label>";
            echo"<textarea type='text' rows='5' class='form-control' id='complaintDetail' placeholder='Report / Complaint detail' name='complaintDetail'></textarea>";
            echo"<div class='alert alert-danger hidden' id='complaintDetailerrbox'></div>";
        echo"</div>";
        echo"<div class='form-group'>";
            echo"<label class='control-label' for='complainerEmail'>Your email id* :</label>";
            echo"<input type='email' class='form-control' id='complainerEmail' placeholder='Your email id' name='complainerEmail'>";
            echo"<div class='alert alert-danger hidden' id='complainerEmailerrbox'></div>";
        echo"</div>";
        echo"<div class='form-group'>";
            echo"<div class='g-recaptcha' data-sitekey='**************'></div>";
        echo"</div>";
        echo"<button type='button' id='complaintsubmit' class='btn btn-primary btn-block'>Submit</button>";
    echo"</form>";
    echo"</div>";
    echo"<div class='modal-footer'>";
    echo"<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>";
    echo"</div>";
}
    catch(PDOException $e)
    {
        echo "Connection failed: " . $e->getMessage();
    }
$db = null;
exit;
}
?>

Я прочитал много ответов с этого сайта, но не смог найти ответ.В моем custom.js, который является внешним файлом, у меня есть свой собственный плагин проверки, который отлично работает с другими страницами, но не проверяет этот мод начальной загрузки, и я думаю, что причина в том, что этот мод загружается после загрузки DOM или, возможно, он исходит от phpстраница, поэтому это происходит.Может кто-нибудь помочь мне, как я могу проверить это из файла custom.js, потому что я не получаю никакой ошибки, кажется, что этот модальный не существует вообще, но этот модальный отрисовывает отлично, только проверка не работает.Когда я помещаю код проверки на той же странице (complaintmodalshow.php), он работает нормально.Я не хочу этого делать, я хочу хранить все свои js-коды в одном месте.Может кто-нибудь предложить мне лучшее решение?Вот мой код проверки только для лучшего обзора.

"use strict";
$(document).ready(function(){
function showerror(errbox, errcontent){
        if($(errbox).hasClass("hidden")){
            $(errbox).removeClass("hidden");
            $(errbox).html(errcontent);
        }
    }
    function hideerror(errbox, errcontent){
        if(!$(errbox).hasClass("hidden")){
            $(errbox).html(errcontent);
            $(errbox).addClass("hidden");
        }
    }
(function ($){
$.fn.alphanumericspace = function(element, errbox){
var alphanumericspace = /^[a-zA-Z 0-9.,]*$/; /*test, true if matches otherwise false*/
    if(!alphanumericspace.test(element)){
        errcontent = "Only alphabets, numbers, dot, comma are allowed.";
        showerror(errbox, errcontent);
    }
    if(alphanumericspace.test(element)){
        if(element != " " && element.length>0){
            errcontent = "";
            hideerror(errbox, errcontent);
            return "no error";
        }
    }
}
function keepcheckingemail(element, errbox){
var emailfilter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; /*test, true if matches otherwise false*/
    $("#email").keyup(function(){
        if(!emailfilter.test(element)){
            errcontent = "invalid email";
            showerror(errbox, errcontent);
        }
        if(emailfilter.test(element)){
            if(element != " " && element.length>0){
                errcontent = "";
                hideerror(errbox, errcontent);
                return "no error";
            }
        }
    });
}
$.fn.emailfil = function(element, errbox){
var emailfilter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; /*test, true if matches otherwise false*/
    if(!emailfilter.test(element)){
        errcontent = "invalid email";
        showerror(errbox, errcontent);
        $("#email").focus();
        keepcheckingemail(element);
    }
    if(emailfilter.test(element)){
        if(element != " " && element.length>0){
            errcontent = "";
            hideerror(errbox, errcontent);
            return "no error";
        }
    }
}
}(jQuery));
$("#complaintAbout").keyup(function(){
    alert("complaintAbout");
    complaintAbout = $("#complaintAbout").val();
    errbox = $("#complaintAbouterrbox");
    complaintAbouterr = $(this).alphanumericspace(complaintAbout, errbox);
    if(complaintAbouterr === "no error"){
        complaintAbouterr = "no";
    }
});
$("#complaintDetail").keyup(function(){
    complaintDetail = $("#complaintDetail").val();
    errbox = $("#complaintDetailerrbox");
    complaintDetailerr = $(this).alphanumericspace(complaintDetail, errbox);
    if(complaintDetailerr === "no error"){
        complaintDetailerr = "no";
    }
});
$("#complainerEmail").focusout(function(){
    complainerEmail = $("#complainerEmail").val();
    errbox = $("#complainerEmailerrbox");
    complainerEmailerr = $(this).emailfil(complainerEmail, errbox);
    if(complainerEmailerr === "no error"){
        complainerEmailerr = "no";
    }
});
});

1 Ответ

0 голосов
/ 26 сентября 2018

хорошо, так что я выяснил, в чем была проблема, и я собираюсь ответить на свой вопрос на тот случай, если кто-то еще ищет это решение:

проблема: проблема заключалась в том, что мой загрузочный модал загружался после загрузки DOM, потому что я использую php для этого, и этот модальный загружается в определенной ситуации, как вы можете видеть в моем вопросе, и это означает, что мой проверочный плагин загружается перед этим модальным, так что плагин не смогчтобы подтвердить это.Чтобы достичь желаемого решения, я должен предоставить селектор для jquery, который должен уже присутствовать при загрузке js-файлов, поэтому я немного изменил свою функцию и добавил еще одну строку, которая упоминается ниже

$(".cbgoverlay").on("click", function (){
//old plugin puts inside
});

сейчас здесьэто главный трюк, этот класс "cbgoverlay" уже существует, когда моя страница загружается, и остаток модального кода будет добавлен позже, поэтому, когда пользователь нажимает на модал, эта функция запускается первой, а после этого внутри функции выбирает элементкоторый рендерит или загружает позже через страницу php.Чтобы понять эту логику, вы должны правильно прочитать весь мой вопрос.окончательное решение здесь.

"use strict";
$(document).ready(function(){
/*complaint modal starts*/
var complaintid, complaintAbout, errbox, complaintAbouterr, errcontent, complaintDetail, robotError, complaintDetailerr;
var complainerEmail, complainerEmailerr, recaptcha;
$('.complaintId').on('click',function(){
    complaintid=(this.id);
    $.ajax({
        method: 'POST',
        url: 'complaintmodalshow.php',
        data: {id:complaintid},
        success: function(data){
            $(".cbgoverlay").html(data);
            $('#complaintModal').modal({
                show:true
            });
        }
    });
});
function showerror(errbox, errcontent){
        if($(errbox).hasClass("hidden")){
            $(errbox).removeClass("hidden");
            $(errbox).html(errcontent);
        }
    }
    function hideerror(errbox, errcontent){
        if(!$(errbox).hasClass("hidden")){
            $(errbox).html(errcontent);
            $(errbox).addClass("hidden");
        }
    }
(function ($){
$.fn.alphanumericspace = function(element, errbox){
var alphanumericspace = /^[a-zA-Z 0-9.,]*$/; /*test, true if matches otherwise false*/
    if(!alphanumericspace.test(element)){
        errcontent = "Only alphabets, numbers, dot, comma are allowed.";
        showerror(errbox, errcontent);
    }
    if(alphanumericspace.test(element)){
        if(element != " " && element.length>0){
            errcontent = "";
            hideerror(errbox, errcontent);
            return "no error";
        }
    }
}
function keepcheckingemail(element, errbox){
var emailfilter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; /*test, true if matches otherwise false*/
    $("#email").keyup(function(){
        if(!emailfilter.test(element)){
            errcontent = "invalid email";
            showerror(errbox, errcontent);
        }
        if(emailfilter.test(element)){
            if(element != " " && element.length>0){
                errcontent = "";
                hideerror(errbox, errcontent);
                return "no error";
            }
        }
    });
}
$.fn.emailfil = function(element, errbox){
var emailfilter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; /*test, true if matches otherwise false*/
    if(!emailfilter.test(element)){
        errcontent = "invalid email";
        showerror(errbox, errcontent);
        $("#email").focus();
        keepcheckingemail(element);
    }
    if(emailfilter.test(element)){
        if(element != " " && element.length>0){
            errcontent = "";
            hideerror(errbox, errcontent);
            return "no error";
        }
    }
}
}(jQuery));
$(".cbgoverlay").on("click", function (){
    $("#complaintAbout").keyup(function(){
        complaintAbout = $("#complaintAbout").val();
        errbox = $("#complaintAbouterrbox");
        complaintAbouterr = $(this).alphanumericspace(complaintAbout, errbox);
        if(complaintAbouterr === "no error"){
            complaintAbouterr = "no";
        }
    });
    $("#complaintDetail").keyup(function(){
        complaintDetail = $("#complaintDetail").val();
        errbox = $("#complaintDetailerrbox");
        complaintDetailerr = $(this).alphanumericspace(complaintDetail, errbox);
        if(complaintDetailerr === "no error"){
            complaintDetailerr = "no";
        }
    });
    $("#complainerEmail").focusout(function(){
        complainerEmail = $("#complainerEmail").val();
        errbox = $("#complainerEmailerrbox");
        complainerEmailerr = $(this).emailfil(complainerEmail, errbox);
        if(complainerEmailerr === "no error"){
            complainerEmailerr = "no";
        }
    });
});
/*complaint modal ends*/
});

Используя этот код, вы сможете загрузить модальный со страницы php, которая упоминалась выше в вопросе, и вы также сможете проверить форму.Удачи.Продолжайте учиться.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...