简体   繁体   English

无需重新加载页面即可提交表单

[英]Submit form without page reloading

I have a classifieds website, and on the page where ads are showed, I am creating a "Send a tip to a friend" form...我有一个分类广告网站,在展示广告的页面上,我正在创建一个“向朋友发送提示”表单...

So anybody who wants can send a tip of the ad to some friends email-adress.因此,任何想要的人都可以将广告提示发送给一些朋友的电子邮件地址。

I am guessing the form must be submitted to a php page right?我猜表单必须提交到 php 页面对吗?

<form name="tip" method="post" action="tip.php">
  Tip somebody: 
  <input 
    name="tip_email"
    type="text" 
    size="30" 
    onfocus="tip_div(1);" 
    onblur="tip_div(2);"
  />
  <input type="submit" value="Skicka Tips" />
  <input type="hidden" name="ad_id" />
</form>

When submitting the form, the page gets reloaded... I don't want that...提交表单时,页面会重新加载...我不希望那样...

Is there any way to make it not reload and still send the mail?有没有办法让它不重新加载并仍然发送邮件? Preferrably without ajax or jquery...最好没有 ajax 或 jquery ......

I've found what I think is an easier way.我找到了我认为更简单的方法。 If you put an Iframe in the page, you can redirect the exit of the action there and make it show up.如果您在页面中放置了一个 Iframe,您可以将操作的退出重定向到那里并使其显示出来。 You can do nothing, of course.当然,你什么也做不了。 In that case, you can set the iframe display to none.在这种情况下,您可以将 iframe 显示设置为无。

<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
    <input type="submit" value="Skicka Tips">
    <input type="hidden" name="ad_id" value="2">            
</form>

You'll need to submit an ajax request to send the email without reloading the page.您需要提交 ajax 请求以发送电子邮件而无需重新加载页面。 Take a look at http://api.jquery.com/jQuery.ajax/看看http://api.jquery.com/jQuery.ajax/

Your code should be something along the lines of:你的代码应该是这样的:

$('#submit').click(function() {
    $.ajax({
        url: 'send_email.php',
        type: 'POST',
        data: {
            email: 'email@example.com',
            message: 'hello world!'
        },
        success: function(msg) {
            alert('Email Sent');
        }               
    });
});

The form will submit in the background to the send_email.php page which will need to handle the request and send the email.该表单将在后台提交到需要处理请求并发送电子邮件的send_email.php页面。

You either use AJAX or you你要么使用 AJAX 要么你

  • create and append an iframe to the document创建 iframe 并将其附加到文档
  • set the iframes name to 'foo'将 iframe 名称设置为 'foo'
  • set the forms target to 'foo'将表单目标设置为 'foo'
  • submit提交
  • have the forms action render javascript with 'parent.notify(...)' to give feedback让表单操作使用“parent.notify(...)”呈现 javascript 以提供反馈
  • optionally you can remove the iframe您可以选择删除 iframe

Fastest and easiest way is to use an iframe.最快和最简单的方法是使用 iframe。 Put a frame at the bottom of your page.在页面底部放置一个框架。

<iframe name="frame"></iframe>

And in your form do this.并以您的形式执行此操作。

<form target="frame">
</form>

and to make the frame invisible in your css.并使框架在您的 css 中不可见。

iframe{
  display: none;
}

SUBMITTING THE FORM WITHOUT RELOADING THE PAGE AND GET THE RESULT OF SUBMITTED DATA ON THE SAME PAGE.无需重新加载页面即可提交表单,并在同一页面上获取提交数据的结果。

Here's some of the code I found on the internet that solves this problem : 这是我在互联网上找到的一些解决此问题的代码:

1.) IFRAME 1.)框架

When the form is submitted, The action will be executed and target the specific iframe to reload.当表单被提交时,动作将被执行并针对特定的 iframe 重新加载。

index.php索引.php

<?php
$Submit = isset($_POST['Submit']) ? $_POST['Submit'] : false;
$Name = isset($_POST['Name']) ? $_POST['Name'] : '';
if($Submit){
 echo $Name;
}
?>

iframe_content.php iframe_content.php

 <?php $Submit = isset($_POST['Submit']) ? $_POST['Submit'] : false; $Name = isset($_POST['Name']) ? $_POST['Name'] : ''; if($Submit){ echo $Name; } ?>

2.) AJAX 2.) AJAX

Index.php:索引.php:

<?php 
$name = isset($_POST['name']) ? $_POST['name'] : '';
$descr = isset($_POST['descr']) ? $_POST['descr'] : '';


echo $name;
echo $descr;

?>

server_action.php server_action.php

 <?php $name = isset($_POST['name']) ? $_POST['name'] : ''; $descr = isset($_POST['descr']) ? $_POST['descr'] : ''; echo $name; echo $descr; ?>

Tags: 标签:

It's a must to take help of jquery-ajax in this case.在这种情况下,必须借助jquery-ajax Without ajax , there is currently no solution.没有ajax ,目前没有解决方案。

First, call a JavaScript function when the form is submitted.首先,在提交表单时调用 JavaScript 函数。 Just set onsubmit="func()" .只需设置onsubmit="func()" Even if the function is called, the default action of the submission would be performed.即使调用该函数,也会执行提交的默认操作。 If it is performed there would be no way of stoping the page from refreshing or redirecting.如果执行,将无法阻止页面刷新或重定向。 So, next task is to prevent the default action.因此,下一个任务是阻止默认操作。 Insert the following line at the start of func() .func()的开头插入以下行。

event.preventDefault()

Now, there will be no redirecting or refreshing.现在,不会有重定向或刷新。 So, you simply make an ajax call from func() and do whatever you want to do when call ends.因此,您只需从func()进行 ajax 调用,并在调用结束时执行您想做的任何操作。

Example:例子:

Form:形式:

<form id="form-id" onsubmit="func()">
    <input id="input-id" type="text">
</form>

Javascript: Javascript:

function func(){
    event.preventDefault();
    var newValue = $('#input-field-id').val();
    $.ajax({
        type: 'POST',
        url: '...',
        data: {...},
        datatype: 'JSON',
        success: function(data){...},
        error: function(){...},
    });
}

This should solve your problem.这应该可以解决您的问题。
In this code after submit button click we call jquery ajax and we pass url to post在提交按钮点击后的这段代码中,我们调用 jquery ajax 并将 url 传递给 post
type POST/GET输入 POST/GET
data: data information you can select input fields or any other.数据:您可以选择输入字段或任何其他字段的数据信息。
sucess: callback if everything is ok from server成功:如果服务器一切正常则回调
function parameter text, html or json, response from server函数参数文本,html 或 json,来自服务器的响应
in sucess you can write write warnings if data you got is in some kind of state and so on.如果你得到的数据处于某种状态等,你可以写警告。 or execute your code what to do next.或执行您的代码下一步要做什么。

<form id='tip'>
Tip somebody: <input name="tip_email" id="tip_email" type="text" size="30" onfocus="tip_div(1);" onblur="tip_div(2);"/>
 <input type="submit" id="submit" value="Skicka Tips"/>
 <input type="hidden" id="ad_id" name="ad_id" />
 </form>
<script>
$( "#tip" ).submit(function( e ) {
    e.preventDefault();
    $.ajax({
        url: tip.php,
        type:'POST',
        data:
        {
            tip_email: $('#tip_email').val(),
            ad_id: $('#ad_id').val()
        },
        success: function(msg)
        {

            alert('Email Sent');
        }               
    });
});
</script>

this is exactly how it CAN work without jQuery and AJAX and it's working very well using a simple iFrame.这正是它可以在没有 jQuery 和 AJAX 的情况下工作的方式,并且使用简单的 iFrame 工作得很好。 I LOVE IT, works in Opera10, FF3 and IE6.我喜欢它,适用于 Opera10、FF3 和 IE6。 Thanks to some of the above posters pointing me the right direction, that's the only reason I am posting here:感谢上面的一些海报为我指明了正确的方向,这就是我在这里发帖的唯一原因:

<select name="aAddToPage[65654]" 
onchange="
    if (bCanAddMore) {
        addToPage(65654,this);
    }
    else {
        alert('Could not add another, wait until previous is added.'); 
        this.options[0].selected = true;
    };
" />
<option value="">Add to page..</option>
[more options with values here]</select>

<script type="text/javascript">
function addToPage(iProduct, oSelect){
    iPage = oSelect.options[oSelect.selectedIndex].value;
    if (iPage != "") {
        bCanAddMore = false;
        window.hiddenFrame.document.formFrame.iProduct.value = iProduct;
        window.hiddenFrame.document.formFrame.iAddToPage.value = iPage;
        window.hiddenFrame.document.formFrame.submit();
    }
}
var bCanAddMore = true;</script> 

<iframe name="hiddenFrame" style="display:none;" src="frame.php?p=addProductToPage" onload="bCanAddMore = true;"></iframe>

the php code generating the page that is being called above:生成上面调用的页面的 php 代码:

if( $_GET['p'] == 'addProductToPage' ){  // hidden form processing
  if(!empty($_POST['iAddToPage'])) {
    //.. do something with it.. 
  }
  print('
    <html>
        <body>
            <form name="formFrame" id="formFrameId" style="display:none;" method="POST" action="frame.php?p=addProductToPage" >
                <input type="hidden" name="iProduct" value="" />
                <input type="hidden" name="iAddToPage" value="" />
            </form>
        </body>
    </html>
  ');
}

You can try setting the target attribute of your form to a hidden iframe, so the page containing the form won't get reloaded.您可以尝试将表单的 target 属性设置为隐藏的 iframe,这样包含该表单的页面就不会重新加载。

I tried it with file uploads (which we know can't be done via AJAX), and it worked beautifully.我尝试了文件上传(我们知道不能通过 AJAX 完成),并且效果很好。

Have you tried using an iFrame?您是否尝试过使用 iFrame? No ajax, and the original page will not load.没有ajax,原始页面不会加载。

You can display the submit form as a separate page inside the iframe, and when it gets submitted the outer/container page will not reload.您可以将提交表单显示为 iframe 内的一个单独页面,并且当它被提交时,外部/容器页面将不会重新加载。 This solution will not make use of any kind of ajax.此解决方案不会使用任何类型的 ajax。

function Foo(){  
   event.preventDefault(); 
 $.ajax(   {  
      url:"<?php echo base_url();?>Controllername/ctlr_function",
      type:"POST",
      data:'email='+$("#email").val(),
      success:function(msg)      {  
         alert('You are subscribed');
      }
   }   );
}

I tried many times for a good solution and answer by @taufique helped me to arrive at this answer.我多次尝试寻找一个好的解决方案,@taufique 的回答帮助我得出了这个答案。

NB : Don't forget to put event.preventDefault();注意:不要忘记放置event.preventDefault(); at the beginning of the body of the function .在函数体的开头。

I did something similar to the jquery above, but I needed to reset my form data and graphic attachment canvases.我做了一些类似于上面的 jquery 的事情,但我需要重置我的表单数据和图形附件画布。 So here is what I came up with:所以这就是我想出的:

    <script>
   $(document).ready(function(){

   $("#text_only_radio_button_id").click(function(){
       $("#single_pic_div").hide();
       $("#multi_pic_div").hide();
   });

   $("#pic_radio_button_id").click(function(){
      $("#single_pic_div").show();
      $("#multi_pic_div").hide();
    });

   $("#gallery_radio_button_id").click(function(){
       $("#single_pic_div").hide();
       $("#multi_pic_div").show();
                 });
    $("#my_Submit_button_ID").click(function() {
          $("#single_pic_div").hide();
          $("#multi_pic_div").hide();
          var url = "script_the_form_gets_posted_to.php"; 

       $.ajax({
       type: "POST",
       url: url,
       data: $("#html_form_id").serialize(), 
       success: function(){  
       document.getElementById("html_form_id").reset();
           var canvas=document.getElementById("canvas");
    var canvasA=document.getElementById("canvasA");
    var canvasB=document.getElementById("canvasB");
    var canvasC=document.getElementById("canvasC");
    var canvasD=document.getElementById("canvasD");

              var ctx=canvas.getContext("2d");
              var ctxA=canvasA.getContext("2d");
              var ctxB=canvasB.getContext("2d");
              var ctxC=canvasC.getContext("2d");
              var ctxD=canvasD.getContext("2d");
               ctx.clearRect(0, 0,480,480);
               ctxA.clearRect(0, 0,480,480);
               ctxB.clearRect(0, 0,480,480);        
               ctxC.clearRect(0, 0,480,480);
               ctxD.clearRect(0, 0,480,480);
               } });
           return false;
                });    });
           </script>

That works well for me, for your application of just an html form, we can simplify this jquery code like this:这对我来说效果很好,对于您仅使用 html 表单的应用程序,我们可以像这样简化此 jquery 代码:

       <script>
        $(document).ready(function(){

    $("#my_Submit_button_ID").click(function() {
        var url =  "script_the_form_gets_posted_to.php";
       $.ajax({
       type: "POST",
       url: url,
       data: $("#html_form_id").serialize(), 
       success: function(){  
       document.getElementById("html_form_id").reset();
            } });
           return false;
                });    });
           </script>

如果您不想使用 javascript,页面将重新加载

You will need to use JavaScript without resulting to an iframe (ugly approach).您将需要使用 JavaScript 而不会产生iframe (丑陋的方法)。

You can do it in JavaScript;你可以用 JavaScript 来做; using jQuery will make it painless.使用 jQuery 将使它变得轻松。

I suggest you check out AJAX and Posting.我建议您查看 AJAX 和 Posting。

如果您提交到表单所在的同一页面,您可以编写表单标签而无需操作,它会提交,如下所示

<form method='post'> <!-- you can see there is no action here-->

A further possibility is to make a direct javascript link to your function:另一种可能性是为您的函数创建一个直接的 javascript 链接:

<form action="javascript:your_function();" method="post">

... ...

I don't know JavaScript and I just started to learn PHP, so what helped for me from all those responses was:我不懂 JavaScript,我刚开始学习 PHP,所以所有这些回答对我的帮助是:

  1. Create inedx.php and insert:创建 inedx.php 并插入:
<iframe name="email" style=""></iframe>
<form action="email.php" method="post" target="email">
<input type="email" name="email" >
<input type="submit" name="Submit" value="Submit">
</form>
  1. Create email.php and insert this code to check if you are getting the data (you should see it on index.php in the iframe):创建 email.php 并插入此代码以检查您是否正在获取数据(您应该在 iframe 的 index.php 上看到它):
    <?php
    if (isset($_POST['Submit'])){
    $email = $_POST['email'];
    echo $email;
    }
    ?>
  1. If everything is ok, change the code on email.php to:如果一切正常,请将 email.php 上的代码更改为:
    <?php
    if (isset($_POST['Submit'])){
    $to = $_POST['email'];
    $subject = "Test email";
    $message = "Test message";
    $headers = "From: test@test.com \r\n";
    $headers .= "Reply-To: test@test.com \r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    
    mail($to, $subject, $message, $headers);
    }
    ?>

Hope this helps for all other rookies like me :)希望这对像我这样的所有其他菜鸟有所帮助:)

For anyone using just Javascript, you can try this:对于任何只使用 Javascript 的人,你可以试试这个:

<form action="" method="get" onsubmit="yourFunction(event); return false;">

And in yourFunction() , you can use preventDefault.yourFunction() ,您可以使用 preventDefault。

function yourFunction(event) {
    event.preventDefault();
    //other logic...
}

Here is some jQuery for posting to a php page and getting html back:这是一些用于发布到 php 页面并返回 html 的 jQuery:

$('form').submit(function() {
    $.post('tip.php', function(html) {
       // do what you need in your success callback
    }
    return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM