使用Ajax和PHP的HTML表单不起作用

时间:2022-10-17 11:44:09

Just wondering if anyone can give me a hand?

不知道有没有人能帮我一下?

I am trying to learn bits of Ajax (this language is so confusing) and I am discovering problems its like the script is being totally ignored or maybe im just making a massive amateur mistake.

我正在尝试学习一些Ajax(这门语言是如此的混乱),我发现一些问题,比如脚本被完全忽略了,或者我只是犯了一个巨大的业余错误。

Before I display code I tried to make a Jsfiddle but it doesn't allow a PHP file.

在显示代码之前,我尝试创建一个Jsfiddle,但是它不允许PHP文件。

Html:

Html:

<form  method="post" action="email.php">
        <label for="name">Name</label>
         <input class="form-control" type="text" id="name" name="name" placeholder="Name">
         <label for="email">Email Address</label>
    <input class="form-control" type="email" id="email" name="email" placeholder="Email Address">
    <label for="phone">Phone Number</label>
    <input class="form-control" type="phone" id="phone" name="phone" placeholder="Phone Number">
    <label for="message">Message</label>
    <textarea placeholder="Message" name="comments" id="comments" class="form-control" rows="5"></textarea>
    <button type="submit" id="submit_button" class="btn btn-lg btn-success">Send</button>
    </form>

PHP (email.php):

PHP(email.php):

<?php
if(isset($_POST['email'])) {

$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // not required
$comments = $_POST['comments']; // required

// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "test@email.com";
//$email_also ="test@yahoo.com";
$email_subject = $name . " Website Inquiry";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Phone: ".clean_string($phone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";


// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
//@mail($email_also, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
<!--Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>

Ajax:

Ajax:

<script type="text/javascript">
$(document).ready(function() {  
$("#submit_button").click, (function() {
// Get all of the values from the input fields through their ID's
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var comments = $("#comments").val();

// Validate the form to make sure that all of the required fields are not left empty
if(first_name != ''
&& email != ''
&& comments != '')
{
   $.ajax({
      url: "email.php",
      type: "POST",
      data: ({
           first_name: name,
           email: email,
           phone: phone,
           comments: comments
       }),
      success: function(data) 
      {
      alert("Message has been received");// You might want to display a message telling the user that the form was successfully filled out.
      }
  });
}

if(name == ''
|| email == ''
|| comments == '')
{
    alert("You left one of the required fields empty");
}
});
});
</script>

The end goal is to make a php form that runs inline on a document so no page refreshes

最终目标是创建一个在文档上内联运行的php表单,这样就不会刷新页面

If anyone can help it will be much appreciated.

如果有人能帮忙,我们将不胜感激。

3 个解决方案

#1


1  

If you have a submit button(type="submit") and action="pageUrl" in the form, when you click that button will redirect to pageUrl. You can cancel the postback produced when submit button is clicked:

如果表单中有一个submit按钮(type="submit")和action="pageUrl",那么单击该按钮时,该按钮将重定向到pageUrl。您可以取消点击提交按钮时产生的回发:

<script type="text/javascript">
$("#submit_button").click(function(event) {
    event.preventDefault(); //cancel postback
    // Get all of the values from the input fields through their ID's
    var name = $("#name").val();
    var email = $("#email").val();
    var phone = $("#phone").val();
    var comments = $("#comments").val();
    if(name != '' && email != '' && comments != '')
    {
        var postData = {
                       first_name: name,
                       email: email,
                       phone: phone,
                       comments: comments
                      };

        //ajax:
        $.post("email.php", data: postData, function(response){
            alert("Message from email.php: " + response);
        });
    }
    else
    {
    alert("You left one of the required fields empty");
    }   
});
</script>

Or using ajax() function:

或使用ajax()函数:

<script type="text/javascript">
$(document).ready(function() {  
    $("#submit_button").click(function(event) {
        event.preventDefault();//cancel postback
        // Get all of the values from the input fields through their ID's
        var name = $("#name").val();
        var email = $("#email").val();
        var phone = $("#phone").val();
        var comments = $("#comments").val();

        // Validate the form to make sure that all of the required fields are not left empty
        //if(first_name != '' <-- ERROR: variable does not exist.
        if(name != '' && email != '' && comments != '')
        {
           $.ajax({
              url: "email.php",
              type: "POST",
              data: {
                   first_name: name,
                   email: email,
                   phone: phone,
                   comments: comments
               },
              success: function(data) 
              {
                // You might want to display a message telling 
                //the user that the form was successfully filled out.
                alert("Message has been received");
              }
          });
        }
        else
        {
        alert("You left one of the required fields empty");
        }    
    });//click()
});//ready()
</script>

#2


1  

You don't have a "name" attribute on your comments textarea input. Give that a try. I don't believe POST will pick it up if you don't use the name attribute.

在您的评论文本区域输入中没有“name”属性。给它一试。如果不使用name属性,我不相信POST会接收到它。

Also, change this section

同时,改变这一节

$email_subject = $name + " Website Inquiry";

to this...

这……

$email_subject = $name . " Website Inquiry";

PHP concatenates strings using the . javascript uses a +

PHP使用。javascript使用+

#3


1  

After applying @magnified 's answer, it will still redirect to the email.php as a page when submit button is clicked...

在应用@ magnis的答案后,它仍然会重新指向电子邮件。当单击submit按钮时,php作为一个页面……

Here's the fix. This line

这是修复。这条线

$("#submit_button").click, (function() {

should be like this

应该是这样

$("#submit_button").click(function() {

The comma probably came in as a typo probably. Also, since you're using ajax to submit the form,

这个逗号可能是输入错误。而且,由于您使用ajax提交表单,

<form  method="post" action="email.php">

should be

应该是

<form>

and

<button type="submit" id="submit_button"

should be

应该是

<button id="submit_button"

#1


1  

If you have a submit button(type="submit") and action="pageUrl" in the form, when you click that button will redirect to pageUrl. You can cancel the postback produced when submit button is clicked:

如果表单中有一个submit按钮(type="submit")和action="pageUrl",那么单击该按钮时,该按钮将重定向到pageUrl。您可以取消点击提交按钮时产生的回发:

<script type="text/javascript">
$("#submit_button").click(function(event) {
    event.preventDefault(); //cancel postback
    // Get all of the values from the input fields through their ID's
    var name = $("#name").val();
    var email = $("#email").val();
    var phone = $("#phone").val();
    var comments = $("#comments").val();
    if(name != '' && email != '' && comments != '')
    {
        var postData = {
                       first_name: name,
                       email: email,
                       phone: phone,
                       comments: comments
                      };

        //ajax:
        $.post("email.php", data: postData, function(response){
            alert("Message from email.php: " + response);
        });
    }
    else
    {
    alert("You left one of the required fields empty");
    }   
});
</script>

Or using ajax() function:

或使用ajax()函数:

<script type="text/javascript">
$(document).ready(function() {  
    $("#submit_button").click(function(event) {
        event.preventDefault();//cancel postback
        // Get all of the values from the input fields through their ID's
        var name = $("#name").val();
        var email = $("#email").val();
        var phone = $("#phone").val();
        var comments = $("#comments").val();

        // Validate the form to make sure that all of the required fields are not left empty
        //if(first_name != '' <-- ERROR: variable does not exist.
        if(name != '' && email != '' && comments != '')
        {
           $.ajax({
              url: "email.php",
              type: "POST",
              data: {
                   first_name: name,
                   email: email,
                   phone: phone,
                   comments: comments
               },
              success: function(data) 
              {
                // You might want to display a message telling 
                //the user that the form was successfully filled out.
                alert("Message has been received");
              }
          });
        }
        else
        {
        alert("You left one of the required fields empty");
        }    
    });//click()
});//ready()
</script>

#2


1  

You don't have a "name" attribute on your comments textarea input. Give that a try. I don't believe POST will pick it up if you don't use the name attribute.

在您的评论文本区域输入中没有“name”属性。给它一试。如果不使用name属性,我不相信POST会接收到它。

Also, change this section

同时,改变这一节

$email_subject = $name + " Website Inquiry";

to this...

这……

$email_subject = $name . " Website Inquiry";

PHP concatenates strings using the . javascript uses a +

PHP使用。javascript使用+

#3


1  

After applying @magnified 's answer, it will still redirect to the email.php as a page when submit button is clicked...

在应用@ magnis的答案后,它仍然会重新指向电子邮件。当单击submit按钮时,php作为一个页面……

Here's the fix. This line

这是修复。这条线

$("#submit_button").click, (function() {

should be like this

应该是这样

$("#submit_button").click(function() {

The comma probably came in as a typo probably. Also, since you're using ajax to submit the form,

这个逗号可能是输入错误。而且,由于您使用ajax提交表单,

<form  method="post" action="email.php">

should be

应该是

<form>

and

<button type="submit" id="submit_button"

should be

应该是

<button id="submit_button"