dongyu7074 2014-03-08 17:41
浏览 71

如何通过以下方式提交表单:PHP发送电子邮件,使用Ajax进行无屏幕刷新,并在没有屏幕刷新的情况下在表单旁边发布消息?

When the user clicks on the submit button I need: (1) The form data to be sent to me via email using PHP, without refreshing the page. (2) A thank you message to appear next to the form using Ajax.

I've got most of it working. I'm not to sure what coding I need to make the page NOT refresh as the PHP script is sending the form data to me via email. Also, once the PHP script is done running, how do I get the Ajax code to run? I've done a ton of research and have found a lot of people use jQuery to resolve this issue. However, I am not using jQuery for this just JavaScript. I know I am close, but need some help. Here is my code thus far:

PHP - Just sends the form data to me via email:

<?php
$persons_name = $_POST['fname'];
$email_address = $_POST['email'];
$comments_questions = $_POST['moreinfo'];

$to = 'fireplace_tea@yahoo.com';
$subject = 'Email - JulesMyers.com';
$msg = "$persons_name has sent an email.
" .
"You can reply to $persons_name at: $email_address
" .
"Question or Comment: $comments_questions
";
mail($to, $subject, $msg, 'From: ' . $email_address);
?>

HTML Form:

<form id="contactMe" method="post" action="contact.php">
 <input type="text" class="inputElement initialColor" name="fname" id="fname">
 <input type="text" class="inputElement initialColor" name="email" id="email">
 <textarea rows="6" class="inputElement" name="moreinfo" id="moreinfo"> </textarea>
 <input type="submit" class="sendButton" id="submitbutton" value="Send">
</form> 
<div class="errormsg"></div>
<div class="formsent"></div>

Ajax: I have the Ajax working when I click the formsent div, but I need it to run after the PHP script does. Is there an event I can listen for?

(function() {
  var httpRequest;
  var b = document.querySelector('.formsent');
  b.onclick = function() { makeRequest('thanks.txt'); };

  function makeRequest(url) 
  {
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
      try {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } 
      catch (e) {
        try {
          httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) {}
      }
    }

    httpRequest.onreadystatechange = alertContents;
    httpRequest.open('POST', url);
    httpRequest.send();
  }

  function alertContents() {
    if (httpRequest.readyState === 4) 
    {
      if (httpRequest.status === 200) 
      {
        /*alert(httpRequest.responseText);*/
        b.innerHTML = httpRequest.responseText;
      } 
    }
  }
})();

Thanks for any help. :)

  • 写回答

1条回答 默认 最新

  • douzhuangxuan3268 2014-03-10 11:14
    关注

    WooHoo! I figured it out without using jQuery...in other words I did it the long way. I did a ton of research and trying things out. How it works is when the user clicks on the button labeled submit JavaScript\DOM gets and stores the values from the three form fields, than XMLhttpRequest\AJAX gets the values that JavaScript\DOM stored and sends them to the PHP file, than the PHP file sends me an email with the form data, and finally httpRequest.responseText puts a thank you message next to the form for the user to see. All of this gets done withOUT the page refreshing. Yeah! Here is the coding that works:

    HTML

    <form id="contactMe">
     <input type="text" class="inputElement initialColor" name="fname" id="fname">
     <input type="text" class="inputElement initialColor" name="email" id="email">
     <textarea rows="6" class="inputElement" name="moreinfo" id="moreinfo"> </textarea>
     <input type="button" class="sendButton" id="submitbutton" value="Send">
    </form> 
    <div class="errormsg"></div>
    <div class="formsent"></div>
    

    JavaScript

    function makeRequest()
    {
        var httpRequest;
        var personName = document.getElementById('fname').value;
        var emailAddress = document.getElementById('email').value;
        var comments = document.getElementById('moreinfo').value;
    
        if (window.XMLHttpRequest) { 
          httpRequest = new XMLHttpRequest();
        } else if (window.ActiveXObject) { 
          try {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
          } 
          catch (e) {
            try {
              httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (e) {}
          }
        }
    
        httpRequest.onreadystatechange = alertContents;
        httpRequest.open("GET", "contact.php?name="+personName+"&email="+emailAddress+"&comment="+comments, true);
        httpRequest.send();
    
        function alertContents() 
          {
            if (httpRequest.readyState === 4 && httpRequest.status === 200) 
            {
                var thankYou = document.querySelector('.formsent');
                thankYou.innerHTML = httpRequest.responseText;
    
                var clearForm = document.getElementById('contactMe');
                clearForm.reset();
            }
          }
    }
    

    PHP

    <?php
    $name = $_GET['name'];
    $email = $_GET['email'];
    $comment = $_GET['comment'];
    
    $to = 'email@fakeDomain.fake';
    $subject = 'Email From Website Form';
    $msg = "$name has sent an email.
    " .
    "You can reply to $name at: $email
    " .
    "Question or Comment: $comment
    ";
    mail($to, $subject, $msg, 'From: ' . $email); 
    
    echo "Thank you " . $name . ".<br>";
    echo "The form has been sent.";
    ?>
    

    The hardest part was figuring out how to pass variables from JavaScript to PHP. It took time to find really good full examples, and to also find explanations of how it works. Here are a couple of resources I found very helpful:
    tutorials2learn.com/tutorials/scripts/ajax-scripts/submit-html-form-ajax.html
    javascriptkit.com/dhtmltutors/ajaxgetpost.shtml
    javascriptkit.com/dhtmltutors/ajaxgetpost2.shtml
    openjs.com/articles/ajax_xmlhttp_using_post.php
    webcheatsheet.com/php/passing_javascript_variables_php.php
    stackoverflow.com/questions/13840429/reference-why-does-the-php-or-other-server-side-code-in-my-javascript-not-wor

    A few notes:
    * I used AJAX (XMLHttpRequest object) to open a communication line between JavaScript and PHP.
    * This entire operation can be done in jQuery with less lines of coding. But, I wanted to know how it worked the long way. So, now when I look at the jQuery coding I understand what it is doing.

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效