Search code examples
phpjqueryformsbootstrap-modalformvalidation.io

Form validation doesn't works in bootstrap


I have a "little" problem with my bootstrap modal. I'm loading into myModal a form created in temp.php file. Then I try to send this form to the save.php file using AJAX. Everything is OK but form validation doesn't works ( didn't checked if is empty before submitting the form). If I hard coding my form in the modal-body everything works fine. The problem occurs only when I load this form from external .php file... Any suggestions how to make form validation works in the right way? Thanks in advance!

My index.php file:

    <html lang="en">
<head>
    <title></title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../bootstrap/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
    <script src="../jquery/jquery.min.js"></script>
    <script src="../bootstrap/js/bootstrap.min.js"></script>
</head>

<body>
<button class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal" data-backdrop="static" onClick="fillModal('temp.php', 'modalTitle');">Open modal</button>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog" style="width:1650px;">
    <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title" id="modal-header">
                
                </h4>
            </div>
            <div class="modal-body my_container-fluid" id="modal-body">

            </div>
            <div class="modal-footer">
                <button type="submit" form="myForm" class="btn btn-success btn-sm" id="save">Save</button>
                <button type="button" class="btn btn-danger danger btn-sm" data-dismiss="modal" id="cancel">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
function fillModal(str, title) {
    var xhttp;
    document.getElementById("modal-body").innerHTML = "";
    document.getElementById("modal-header").innerHTML = title;

    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
        document.getElementById("modal-body").innerHTML = this.responseText;
        }
    };
  xhttp.open("POST", str, true);
  xhttp.send();
}



//Submit form with AJAX
$(document).ready(function(){
    $("#save").click(function(event){
        event.preventDefault();                 //prevent default action 
        
    // AJAX request
        $.ajax({
            url : "save.php",                   //form action url
            type: 'POST',                       //form method
            data : $("#myForm").serialize(),    //encode form elements for submission
            success: function(response){ 
                $('.modal-body').html(response);
            },
            error: function(){
                $('.modal-body').html('Error...');
            }   
        
        });
    });
});
</script>

</body>
</html>

This is my temp.php file:

<?php
    echo "<form name=\"myForm\" id=\"myForm\" data-target=\"#myModal\">\n";
    echo "<table class=\"table table-bordered table-condensed\" style=\"width:1240px;\">\n";
    echo "<thead>\n";
    echo "  <tr>\n";
    echo "      <th class=\"bg-success th\" style=\"width: 170px; max-width: 170px;\">Sample 1</th>\n";
    echo "      <th class=\"bg-success th\" style=\"width: 170px; max-width: 170px;\">Sample 2</th>\n";
    echo "      <th class=\"bg-primary th\" style=\"width: 130px; max-width: 130px;\">Sample 3</th>\n";
    echo "      <th class=\"bg-primary th\" style=\"width: 130px; max-width: 130px;\">Sample 4</th>\n";
    echo "      <th class=\"bg-primary th\" style=\"width: 130px; max-width: 130px;\">Sample 5</th>\n";
    echo "      <th class=\"bg-primary th\" style=\"width: 50px; max-width: 50px;\">Sample 6\n";
    echo "      <th class=\"active th\" style=\"width: 130px; max-width: 130px;\">Sample 7</th>\n";
    echo "      <th class=\"active th\" style=\"width: 100px; max-width: 100px;\">Sample 8</th>\n";
    echo "      <th class=\"active th\" style=\"width: 200px; max-width: 200px;\">Sample 9</th>\n";
    echo "  </tr>\n";
    echo "</thead>\n";
    echo "  <tr>\n";
    echo "      <td style=\"width: 170px; max-width: 170px;\"><input class=\"form-control input-sm\" type=\"text\" name=\"Sample_1\" placeholder=\"Sample 1...\" reguired></td>\n";
    echo "      <td style=\"width: 170px; max-width: 170px;\"><input class=\"form-control input-sm\" type=\"text\" name=\"Sample_2\" placeholder=\"Sample 2...\" reguired></td>\n";
    echo "      <td style=\"width: 130px; max-width: 130px;\"><input class=\"form-control input-sm\" type=\"text\" name=\"Sample_3\" placeholder=\"Sample 3...\"></td>\n";
    echo "      <td style=\"width: 130px; max-width: 130px;\"><input class=\"form-control input-sm\" type=\"text\" name=\"Sample_4\" placeholder=\"Sample 4...\"></td>\n";
    echo "      <td style=\"width: 130px; max-width: 130px;\"><input class=\"form-control input-sm\" type=\"text\" name=\"Sample_5\" placeholder=\"Sample 5...\"></td>\n";
    echo "      <td style=\"width: 50px; max-width: 50px;\"><input class=\"form-control input-sm\" type=\"text\" name=\"Sample_6\" placeholder=\"Sample 6...\"></td>\n";
    echo "      <td style=\"width: 130px; max-width: 130px;\"><input class=\"form-control input-sm\" type=\"number\" name=\"Sample_7\" placeholder=\"Sample 7...\"></td>\n";
    echo "      <td style=\"width: 100px; max-width: 100px;\"><input  class=\"form-control input-sm\"type=\"text\" name=\"Sample_8\" placeholder=\"Sample 8...\"></td>\n";
    echo "      <td style=\"width: 200px; max-width: 200px;\"><input class=\"form-control input-sm\" type=\"text\" name=\"Sample_9\" placeholder=\"Sample 9...\"></td>\n";
    echo "  </tr>\n";
    echo "</tale>\n";
    echo "<input type=\"hidden\" name=\"act\" value=\"addNew\">\n";
    echo "</form>\n";
?>

Solution

  • xmlhttprequest IS ajax. $.ajax is the same as xhttp....

    element.load(url) does ajax too

    1. Replace reguired with required (spelling)
    2. give the required fields an empty value
    3. replace $("#save").click(function(event) { with
      $("#modal-body").on("submit","#myForm", function(event) {
      because you need to submit the form to execute the validation - the e.preventDefault stops the submission so you can do the ajax
    4. Replace
    function fillModal(str, title) {
        var xhttp;
        document.getElementById("modal-body").innerHTML = "";
        document.getElementById("modal-header").innerHTML = title;
    
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
            document.getElementById("modal-body").innerHTML = this.responseText;
            }
        };
      xhttp.open("POST", str, true);
      xhttp.send();
    }
    

    with this jquery

    $('[data-target="#myModal"]').on("click", function() {
      $("#modal-header").html($(this).data("title")); 
      $("#modal-body").empty().load($(this).data("url")) 
    }
    

    and change the button from

    <button class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal" data-backdrop="static" onClick="fillModal('temp.php', 'modalTitle');">Open modal</button>

    to

    <button class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal" data-backdrop="static" data-title="modalTitle" data-url="temp.php">Open modal</button>

    $(function() {
    
      $('[data-target="#myModal"]').on("click", function() {
        $("#modal-header").html($(this).data("title")); 
        // $("#modal-body").load($(this).data("url")); 
        
        // the code below is an example - uncomment above and delete below
        $("#modal-body").html(`<form name="myForm" id="myForm" data-target="#myModal">
    <table class="table table-bordered table-condensed" style="width:1240px;">
    <thead>
      <tr>
          <th class="bg-success th" style="width: 170px; max-width: 170px;">Sample 1</th>
          <th class="bg-success th" style="width: 170px; max-width: 170px;">Sample 2</th>
          <th class="bg-primary th" style="width: 130px; max-width: 130px;">Sample 3</th>
          <th class="bg-primary th" style="width: 130px; max-width: 130px;">Sample 4</th>
          <th class="bg-primary th" style="width: 130px; max-width: 130px;">Sample 5</th>
          <th class="bg-primary th" style="width: 50px; max-width: 50px;">Sample 6
          <th class="active th" style="width: 130px; max-width: 130px;">Sample 7</th>
          <th class="active th" style="width: 100px; max-width: 100px;">Sample 8</th>
          <th class="active th" style="width: 200px; max-width: 200px;">Sample 9</th>
      </tr>
    </thead>
      <tr>
          <td style="width: 170px; max-width: 170px;"><input class="form-control input-sm" type="text" name="Sample_1" placeholder="Sample 1..." required value=""></td>
          <td style="width: 170px; max-width: 170px;"><input class="form-control input-sm" type="text" name="Sample_2" placeholder="Sample 2..." required value=""></td>
          <td style="width: 130px; max-width: 130px;"><input class="form-control input-sm" type="text" name="Sample_3" placeholder="Sample 3..."></td>
          <td style="width: 130px; max-width: 130px;"><input class="form-control input-sm" type="text" name="Sample_4" placeholder="Sample 4..."></td>
          <td style="width: 130px; max-width: 130px;"><input class="form-control input-sm" type="text" name="Sample_5" placeholder="Sample 5..."></td>
          <td style="width: 50px; max-width: 50px;"><input class="form-control input-sm" type="text" name="Sample_6" placeholder="Sample 6..."></td>
          <td style="width: 130px; max-width: 130px;"><input class="form-control input-sm" type="number" name="Sample_7" placeholder="Sample 7..."></td>
          <td style="width: 100px; max-width: 100px;"><input  class="form-control input-sm"type="text" name="Sample_8" placeholder="Sample 8..."></td>
          <td style="width: 200px; max-width: 200px;"><input class="form-control input-sm" type="text" name="Sample_9" placeholder="Sample 9..."></td>
      </tr>
    </tale>
    <input type="hidden" name="act" value="addNew">
    </form>`)
      })
    
    
      $("#modal-body").on("submit","#myForm", function(event) {
        event.preventDefault(); //prevent default action 
    
        // AJAX request
        $.ajax({
          url: "save.php", //form action url
          type: 'POST', //form method
          data: $("#myForm").serialize(), //encode form elements for submission
          success: function(response) {
            $('.modal-body').html(response);
          },
          error: function() {
            $('.modal-body').html('Error...');
          }
    
        });
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    
    <button class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal" data-title="modal title 1" data-url="temp..php" data-backdrop="static">Open modal 1</button>
    
    
    <button class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal" data-title="modal title 2" data-url="temp..php" data-backdrop="static">Open modal 2</button>
    
    <!-- Modal -->
    <div class="modal fade" id="myModal" role="dialog">
      <div class="modal-dialog" style="width:1650px;">
        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title" id="modal-header"></h4>
            <button type="button" class="close" data-dismiss="modal">&times;</button>
          </div>
          <div class="modal-body my_container-fluid" id="modal-body">
    
          </div>
          <div class="modal-footer">
            <button type="submit" form="myForm" class="btn btn-success btn-sm" id="save">Save</button>
            <button type="button" class="btn btn-danger danger btn-sm" data-dismiss="modal" id="cancel">Close</button>
          </div>
        </div>
      </div>
    </div>