0

I have a simple code responsible for pressing the button and then sending the data from the form to the checking file and sending it back to the main file, the problem appears after entering the page - for the data to be sent I have to press the button twice - then it works the first time this button, after refreshing the page again I have to press the button twice again.

$(document).ready(function() {
  $('#myBtn').click(function(e) {
    e.preventDefault();
    var text_1 = $("#text_1").val();
    var text_2 = $("#text_2").val();
    var text_3 = $("#text_3").val();

    $.ajax({
      type: "POST",
      url: "execute.php",
      dataType: "json",
      data: {
        text_1: text_1,
        text_2: text_2,
        text_3: text_3
      },

      success: function(data) {
        if (data.code == "200") {
          alert("Success: " + data.msg);
        } else {
          var modal = document.getElementById("myModal");
          var btn = document.getElementById("myBtn");

          btn.onclick = function() {
            modal.style.display = "block";
          }

          window.onclick = function(event) {
            if (event.target == modal) {
              modal.style.display = "none";
            }
          }
          $(".modal-content").html("<ul>" + data.msg + "</ul>");
        }
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myModal" class="modal">
  <div class="modal-content">
  </div>
</div>
<form role="form" data-toggle="validator">
  <input type="text" id="text_1" placeholder="Text 1">
  <input type="text" id="text_2" placeholder="Text 2">
  <input type="text" id="text_3" placeholder="Text 3">
  <button type="submit" id="myBtn">Send</button>
</form>
mplungjan
  • 169,008
  • 28
  • 173
  • 236

1 Answers1

0

Solved.

I changed

                    var btn = document.getElementById("myBtn");

                    btn.onclick = function(){
                        modal.style.display = "block";
                    }

                    window.onclick = function(event){

On:

                    var modal = document.getElementById("myModal");

                    $(".modal").css("display","block");

                    window.onclick = function(event){