Javascript 表单提交后加载模态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34362470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:13:22  来源:igfitidea点击:

Load modal after form submit

javascriptphpjquerytwitter-bootstrap

提问by ladanta

Relevant page here: http://marcmurray.net/test_sites/cans/news.php

相关页面在这里:http: //marcmurray.net/test_sites/cans/news.php

I've been trying to load a message confirmation modal for a while after the user submits an email, but can't get it to work at all.

在用户提交电子邮件后,我一直在尝试加载消息确认模式一段时间,但根本无法使其正常工作。

So far I've tried echoing the whole script out, triggering the script, and changing the hash in the URL and checking for that, which has worked in other areas of the site.

到目前为止,我已经尝试回显整个脚本,触发脚本,并更改​​ URL 中的哈希值并检查它,这在站点的其他区域也有效。

Adding functions like alerts and echoing text onto the page is working fine, but when I use the show method it doesn't work. That leads me to believe I am either escaping characters wrong, or misunderstand how modals work a little. Can anyone see where I'm messing up?

在页面上添加警报和回显文本等功能工作正常,但是当我使用 show 方法时它不起作用。这让我相信我要么错误地转义字符,要么误解了模态的工作原理。谁能看到我哪里搞砸了?

PHP:

PHP:

<?php
if(isset($_POST["submit"])) {
        // Checking For Blank Fields..
    if($_POST["vname"]==""||$_POST["vemail"]==""||$_POST["sub"]==""||$_POST["msg"]==""){
       echo "Please fill out everything! We need to know who you are, and why you want to get in touch with us!";}
    else
        {
        // Check if the "Sender's Email" input field is filled out
        $email=$_POST['vemail'];
                // Sanitize E-mail Address
        $email =filter_var($email, FILTER_SANITIZE_EMAIL);
                // Validate E-mail Address
        $email= filter_var($email, FILTER_VALIDATE_EMAIL);
        $emailConfirmed=$_POST['vemail'];
        if (!$email){
          echo "Don't forget to include your email adress! Otherwise we can't get back to you.";
                }
                else
                {
                    $subject = $_POST['sub'];
                    $message = $_POST['msg'];
                    $headers =  'From:' . $emailConfirmed . "\r\n"; // Sender's Email
                    $headers .= 'Cc:' . $emailConfirmed . "\r\n"; // Carbon copy to Sender
                    // Message lines should not exceed 70 characters (PHP rule), so wrap it
                    $message = wordwrap($message, 70);
                    // Send Mail By PHP Mail Function
                    mail("[email protected]", $subject, $message, $headers);
                    echo "<script>$('#thankyouModal').modal('show')</script>";
                };
    }
 }
?>

HTML for the modal

模态的 HTML

<div class="modal fade" id="thankyouModal" tabindex="-1" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
          <h4 class="modal-title" id="myModalLabel">Thank you for pre-registering!</h4>
      </div>
      <div class="modal-body">
          <p>Thanks for getting in touch!</p>                     
      </div>    
    </div>
  </div>
</div>

EDIT: Updated code to be simpler than initial question.

编辑:更新的代码比最初的问题更简单。

采纳答案by Swarnendu Paul

Instead of calling modal showmethod upfront let all the assets load first then call the modal showmethod.

modal show先让所有资产加载然后调用modal show方法,而不是预先调用方法。

echo "<script>
         $(window).load(function(){
             $('#thankyouModal').modal('show');
         });
    </script>";

回答by Tyler Pope

Instead of echoing the script why not just detect your form submit with javascript and then display the modal?

与其回显脚本,为什么不直接检测您的表单使用 javascript 提交,然后显示模态?

Something like

就像是

$("form").on('submit', function(){
   $('.modal').show();
})

(If you're using JQuery)

(如果您使用的是 JQuery)

回答by mhrilwan

First problem i see in your example code is, unnecessary \ on following code.echo "<script> \. Remove it

我在您的示例代码中看到的第一个问题是,以下代码中不必要的 \。echo "<script> \. 去掉它

Second: Are you including all required js and css files for boostrap modal? If you are not Please update the code with following lines of code

第二:您是否包含了 boostrap 模式所需的所有 js 和 css 文件?如果您不是请使用以下代码行更新代码

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

At last there is no event triggered to open boostrap modal. Add following code to trigger the modal.

最后没有触发打开boostrap模式的事件。添加以下代码以触发模态。

$(window).load(function(){
     $('#myModal').modal('show');
});

Final code :

最终代码:

echo "<script>
            var newHTML = document.createElement ('div');
            newHTML.innerHTML =
            newHTML = document.createElement ('div');
            newHTML.innerHTML = ' <div id=\"myModal\" class=\"modal fade\" tabindex=\"-1\" role=\"dialog\"> <div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"></div>';
            document.body.appendChild (newHTML);
            $(window).load(function(){
                 $('#myModal').modal('show');
            });
        </script>";

Hope this helps.

希望这可以帮助。

回答by jpganz18

Maybe this is the problem..

也许这就是问题所在..

 echo "<script>$('#thankyouModal').modal('show')</script>";

I would do this....

我会这样做....

$var =   "<script>$(document).ready(function(){
             $('#thankyouModal').modal('show')
          });</script>";

And later print it on the right part inside your head at your html template.

然后在你的 html 模板中将它打印在你头脑中的右侧部分。

Using your option and adding $(document).ready inside the script you are echoing dont think would work...the problem with the last option is that you will echo the script but jquery might not be yet fully loaded and it wont recognize it.

使用您的选项并在您要回显的脚本中添加 $(document).ready 不认为会起作用...最后一个选项的问题是您将回显脚本但 jquery 可能尚未完全加载并且无法识别它.

So, I suggest it to send it as a parameter and then print it.

所以,我建议把它作为参数发送,然后打印出来。

If you are not using a framework and it is hard for you to pass a parameter, you can do it thought the URL and do something like my project.com/result.php?submit=true

如果您没有使用框架并且很难传递参数,则可以通过 URL 进行操作并执行类似我的操作 project.com/result.php?submit=true

and at your frontend you will read that variable

在您的前端,您将读取该变量

Like

喜欢

if(isset($_GET["submit"]) && ($_GET["submit"]) ){
//echo your modal script 
}

回答by Covik

I discovered that .in (sets opacity to 1) class which I believe should be set by Bootstrap does not show after submitting the form.

我发现我认为应该由 Bootstrap 设置的 .in(将不透明度设置为 1)类在提交表单后没有显示。

$('.modal').show().addClass('in');

Btw. you have an error in console

顺便提一句。你在控制台有错误

$(...).parsley(...).on is not a function

回答by Anil Panwar

$('#thankyouModal').submit(function(e) {
    e.preventDefault(); // don't submit multiple times
    this.submit(); // use the native submit method of the form element
     $('#thankyouModal').modal('show'); //Open the model
});

or You can manually create a button after form submit and trigger click on that button to open the modal.

或者您可以在表单提交后手动创建一个按钮并触发单击该按钮以打开模态。

$('#thankyouModal').click(function(e) {
        e.preventDefault(); // don't submit multiple times
        $("form").submit(); // use the native submit method of the form element
 $('<button type="button" id="btnThankYou" class="hidden" data-toggle="modal" data-target="#thankyouModal">ThankYouButton</button>').appendTo('body');

//This will click the button and open the modal
    $("#btnThankYou" ).trigger("click");
    });

回答by secenv

As xkcd149 says, if you mean to load the modal in the same page without reloading, you should be using AJAX requests:

正如 xkcd149 所说,如果您打算在同一页面中加载模式而不重新加载,则应该使用 AJAX 请求:

  1. replace the onsubmit attribute of the form to a function that sends the request data

    window.onload = function() {
      var forms = document.getElementsByTagName("form");
      for(var f in forms) {
        frm[f].onsubmit = xhr; // xhr is the function that sends the XHR
      }
    }
    
  2. in the submit funcion used above, add success and error callbacks:

    function xhr(){
      var client = new XMLHttpRequest();
      ...
      client.onerror = xhrerr;
      client.onreadystatechange = handler;
      client.send(...);
      ...
    }
    
  3. the success function should display the modal if the returned HTTP code is 200 (or whatever you want/need)

    function handler(){
      if (this.readyState == 4 && this.status == 200) {
        var widget = document.getElementById("modal-body");
        // add content to the body of the modal
      } else {
      // manage error
      }
    }
    
  1. 将表单的 onsubmit 属性替换为发送请求数据的函数

    window.onload = function() {
      var forms = document.getElementsByTagName("form");
      for(var f in forms) {
        frm[f].onsubmit = xhr; // xhr is the function that sends the XHR
      }
    }
    
  2. 在上面使用的提交函数中,添加成功和错误回调:

    function xhr(){
      var client = new XMLHttpRequest();
      ...
      client.onerror = xhrerr;
      client.onreadystatechange = handler;
      client.send(...);
      ...
    }
    
  3. 如果返回的 HTTP 代码为 200(或任何您想要/需要的代码),则成功函数应显示模式

    function handler(){
      if (this.readyState == 4 && this.status == 200) {
        var widget = document.getElementById("modal-body");
        // add content to the body of the modal
      } else {
      // manage error
      }
    }
    

回答by Robinson Legaspi

Place this links at your HEAD tag:

将此链接放在您的 HEAD 标签上:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

and then change this:

然后改变这个:

<script>$('#thankyouModal').modal('show')</script>

to:

到:

$(document).ready(function(){
<script>$('#thankyouModal').modal('show')</script>
});

回答by Satyam S

$modal =   "<script>$(document).ready(function(){
         $('#thankyouModal').modal('show')
      });</script>";


if(isset($_GET["submit"]) && ($_GET["submit"]) ){
 // after running other script
 echo $modal; 
}

回答by NewUser

You can try as

你可以试试

$('#thankyouModal').submit(function(e) {
e.preventDefault(); // don't submit multiple times
this.submit(); // use the native submit method of the form element
 $('#thankyouModal').modal('show'); //Open the model
});