【问题标题】:ajax form goes to another page instead of remaining on the same pageajax 表单转到另一个页面而不是留在同一页面上
【发布时间】:2012-09-22 10:16:24
【问题描述】:

我有这个弹出 ajax 表单,它不是发送数据并保持在同一页面上,而是发送数据但将我带到我的表单中的文件 send.php。这是为什么?我在另一个站点上正确地实现了几乎相同的表单。我不知道我在这里做错了什么......

表格:

<form id="form" action="send.php"  name="form" method="post" >

    <input type="text"  id="name" name="name" value="" /><br />

    <input type="text"  id="email" name="email" value=""  /><br />

    <textarea name="message" cols="4" rows="4"  id="message" ></textarea><br />

    <input type="submit" value="" id="submit" title="Send!"/>

</form>

ajax:

<script type="text/javascript">

$(document).ready(function () {
    $('#form').ajaxForm({
        beforeSubmit: validate
    });

    function validate(formData, jqForm, options) {
        var name = $('input[name=name]').fieldValue();
        var email = $('input[name=email]').fieldValue();
        var message = $('textarea[name=message]').fieldValue();

        if (!name[0]) {
            alert('Please enter a value for name');
            return false;
        }
        if (!email[0]) {
            alert('Please enter a value for email');
            return false;
        }
        if (!message[0]) {
            alert('Please enter a value for message');
            return false;
        }

        else {

        $("#prima_form").fadeOut(1000, function () {
            $(this).html("<img src='images/de_multumire.png'/>").fadeIn(2000);
        });

        var message = $('textarea[name=message]').val('');
        var name = $('input[name=name]').val('');
        var email = $('input[name=email]').val('');

} 
}

});

</script>

发送.php:

<?php
        if($_POST){
                $email = $_POST['email'];
                $name = $_POST ['name'];
                $message = $_POST ['message'];
                // response hash
                $ajaxresponse = array('type'=>'', 'message'=>'');

                try {
                        // do some sort of data validations, very simple example below
                        $all_fields = array('name', 'email', 'message');

                        foreach($all_fields as $field){
                                if(empty($_POST[$field])){
                                        throw new Exception('Required field "'.ucfirst($field).'" missing input.');
                                }
                        }

                        // ok, if field validations are ok
                        // now Send Email, ect.

                        // let's assume everything is ok, setup successful response
                        $subject = "New Contact";
                        //get todays date
                        $todayis = date("l, F j, Y, g:i a") ;

                        $message = " $todayis \n
                        Attention: \n\n
                        Please see the message below: \n\n
                        Email Address: $email \n\n
                        Message: $message \n\n

                        ";

                        $from = "From: $email\r\n";


                        //put your email address here
                        mail("contact@xxx.ro", $subject, $message, $from);

                        //prep json response
                        $ajaxresponse['type'] = 'success';
                        $ajaxresponse['message'] = 'Thank You! Will be in touch soon';  
                } catch(Exception $e){
                        $ajaxresponse['type'] = 'error';
                        $ajaxresponse['message'] = $e->getMessage();
                }
                // now we are ready to turn this hash into JSON
                print json_encode($ajaxresponse);
                exit;
        }
?>  

我的 js 控制台给出了这个:

[17:38:03.840] [cycle] terminating; zero elements found by selector @ http://sociallab.ro/js/jquery_003.js:10
--
[17:38:16.012] POST http://sociallab.ro/send.php [HTTP/1.1 200 OK 218ms]

[17:38:16.204] The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol. @ http://sociallab.ro/send.php

谢谢!

【问题讨论】:

  • 这里是使用 ajax 发送表单的方法(顺便说一句,你没有这样做)stackoverflow.com/a/5733859/982924
  • 我设法让它与该示例一起使用,但我无法弄清楚如何在使用该代码提交之前验证每个输入...

标签: php jquery html ajax forms


【解决方案1】:

在纯 Javascript 中,您需要执行以下操作:

function sendWithAjax() {
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "send.php", true);

然后从输入元素中读取值:

    var email = document.getElementById('email').value;
    var name = document.getElementById('name').value;
    var message = document.getElementById('message').value;

您可以在调用 .send() 之前在此处验证表单

(您可能需要使用 escape() 函数转义表单元素的内容)

并将它们放入发送方法中:

    ajax.send("email="+ email +"&name="+ name +"&message="+ message);

并从您的表单代码中删除完整的表单标签。因此您不需要提交按钮,因此将其更改为一个简单的按钮:

<input type="text"  id="name" name="name" value="" /><br />
<input type="text"  id="email" name="email" value=""  /><br />
<textarea name="message" cols="4" rows="4"  id="message" ></textarea><br />
<input type="submit" value="" id="submit" title="Send!" onclick="javascript:sendWithAjax()"/>

要获取 ajax 响应,请使用:

    var response = ajax.responseText;
}

【讨论】:

    【解决方案2】:

    尝试添加这个:

    $('#submit').click(function(){ return false; /* stop html form from submitting*/ })
    

    我相信正在发生的事情是 jquery 正在通过 ajax 发送表单数据,但您并没有像往常一样阻止默认的“提交”按钮提交 html 表单。添加上面的代码应该会停止提交按钮的默认操作(将表单提交到 send.php),从而使您留在当前页面。

    【讨论】:

      【解决方案3】:

      类似:

         $(document).ready(function(event){
              event.preventDefault();
              $('#FORMID').ajaxForm({
                  type: 'POST',
                  dataType: 'json',
                  beforeSubmit: function(){
                  },
                  success: function(resp){
      
                  },
                  error: function(resp){
      
                  }
              });
          });
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-09
        • 2015-05-08
        • 1970-01-01
        • 1970-01-01
        • 2020-06-09
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        相关资源
        最近更新 更多