简体   繁体   English

PHP表单提交无刷新-Ajax无法正常工作

[英]Php Form Submit without Refresh - Ajax not working

I am trying to get get my form to submit without having the page refreshing everytime 我正在尝试让我的表单提交而无需每次刷新页面

However, when I insert the ajax and place the php into a new file the form doesnt submit and I dont understand why? 但是,当我插入ajax并将php放入新文件时,表单没有提交,我也不明白为什么?

Any advice would be appreicated! 任何建议,将不胜感激!

PHP 的PHP

<?php
if(isset($_POST['name'], $_POST['email'], $_POST['phone'], $_POST['message'])){
    //Post data
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    //mail settings
    $to = "arshdsoni@gmail.com";
    $subject = 'Soni Repairs - Support Request';
    $body = <<<EMAIL

Hi There!

My name is $name.

Message: $message.

My email is: $email
Phone Number: $phone

Kind Regards
EMAIL;

    $header = "From: $email";

    if($_POST) {
        if($name == '' || $email == '' || $phone == '' || $message == '') {
            echo $feedback = "<font color='red'> *Please Fill in All Fields!";
        }
        else {
            mail($to, $subject, $body, $header);
            echo $feedback = "<font color='green'> *Message sent! You will receive a reply shortly!";
        }
    }

}

else{
    echo $feedback = "<font color='red'> Missing Params";
}

?>

AJAX AJAX

<script src="http://code.jquery.com/jquery-latest.js"></script>
        <script>
            $(document).ready(function(){

                $("#submitBtn").click(function( event ) {
                    //values
                    var name=document.getElementById('name').value;
                    var email=document.getElementById('email').value;
                    var phone=document.getElementById('phone').value;
                    var message=document.getElementById('message').value;
                    var occasion=document.getElementById('occasion').value;
                    var dataString = $("#contact").serialize();

                    $.ajax({
                        type:"post",
                        url:"php.php",
                        data: dataString,
                        success: function(html) {
                            $('#feedback').html(html);
                        }
                    });
                  event.preventDefault();
                });
            });
        </script>

HTML CODE HERE: http://www.codeply.com/go/e3jAo1WrPl HTML代码在这里: http//www.codeply.com/go/e3jAo1WrPl

The .bind() function may be the way to go with this form, since it binds the action of clicking the button to the event handler. .bind()函数可能是采用这种形式的方式,因为它会将单击按钮的动作绑定到事件处理程序。

It also may be beneficial to have the event.preventDefault() before your ajax call. 在您的ajax调用之前使用event.preventDefault()可能也是有益的。

            $(document).ready(function(){
            $("#submitBtn").bind([boundElement],function( event ) {
                event.preventDefault();
                var name=document.getElementById('name').value;
                var email=document.getElementById('email').value;
                var phone=document.getElementById('phone').value;
                var message=document.getElementById('message').value;
                var occasion=document.getElementById('occasion').value;
                var dataString = $("#contact").serialize();

                $.ajax({
                    type:"post",
                    url:"php.php",
                    data: dataString,
                    success: function(html) {
                        $('#feedback').html(html);
                    }
                });
             return true;
            });
        });

I would recommend double-checking the syntax for the bound element in the .bind() parameters. 我建议仔细检查.bind()参数中绑定元素的语法。 It is single quote marks for referring to a named form element Example HTML: 它是单引号,用于引用命名的表单元素示例HTML:

Here is a suggestion with using a button in stead of a submit. 这是使用按钮代替提交的建议。 I commented out the preventDefault , because it is unnecessary in this case -- we are not actually submitting the form. 我注释掉了preventDefault ,因为在这种情况下这是不必要的-我们实际上不是在提交表单。 This gives us more control. 这给了我们更多的控制权。

The request is submitted. 该请求已提交。 In this case, it obviously fails. 在这种情况下,它显然会失败。 In your case, whether or not it fails is going to depend on what you have going on server side. 对于您而言,它是否失败将取决于您在服务器端所做的事情。

http://plnkr.co/edit/txuxaFUkgFq9SFDcqUdp http://plnkr.co/edit/txuxaFUkgFq9SFDcqUdp

<form action="http://www.yahoo.com" id="contactForm" method="get" target="_blank">
    <div class="innerForm">
        <label for="name">Name:</label>
        <input id="name" name="name" type="text" />
        <label for="phone">Phone:</label>
        <input id="phone" name="phone" type="text" />
        <label for="email">Email:</label>
        <input id="email" name="email" type="text" />
        <label for="occasion">Occasion:</label>
        <input id="occasion" type="text" name="occasion" />
        <label id="messageLabel" for="message">Message:</label>
        <textarea id="message" name="message"></textarea>
        <button id="test">test</button>
        <!--input type="submit" value="Submit" id="submitBtn" name="submit" onclick="return chk();"/ -->
    </div>
    <div id="feedback"></div>
</form>

$(document).ready(function(){
    $("#test").click(function (event) {
      //values
      alert("test clicked");
      var name = document.getElementById('name').value;
      var email = document.getElementById('email').value;
      var phone = document.getElementById('phone').value;
      var message = document.getElementById('message').value;
      var occasion = document.getElementById('occasion').value;
      var dataString = $("#contactForm").serialize();

      $.ajax({
          type: "get",
          url: "http://www.yahoo.com",
          data: dataString,
          success: function (html) {
              alert("success");
              //$('#feedback').html(html);
          },
          error: function(result){
              alert("failure");
          }
      });
      //event.preventDefault();
  });
});

This might help you with your problem: 这可能会帮助您解决问题:

$(document).ready(function() {
    $("#contact").submit(function(event) {
        event.preventDefault();

        var name       = $('#name').val(),
            email      = $('#email').val(),
            phone      = $('#phone').val(),
            message    = $('#message').val(),
            occasion   = $('#occasion').val(),
            dataString = $(this).serialize();

        $.ajax({
            url: 'php.php',
            type: 'post',
            data: dataString,
        })
        .done( function( html ) {
            $( '#feedback' ).html( html );
        })
        .fail( function( response ) {
            console.log( response );
        });

    });
});

Firs of all, you have the form and the submit button, so when you press the button, the event 'submit' is triggered, so you prevent the event to be fired, then you do your coding, the variables, but I cannot understand why you declare all those, if you don't use them, but that's up to you. 首先,您具有表单和“提交”按钮,因此,当您按下按钮时,会触发事件“提交”,因此您可以防止触发事件,然后对变量进行编码,但是我无法理解为什么要声明所有这些内容(如果不使用它们的话),但这取决于您。

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

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