使用ajax在php中的一个页面上提交多个表单用于发送邮件

In Functionality, I have 5 button for submit contact form on one page. This form is opened the popup.

When I send the contact form on php using ajax call on same page for single form, I get the data by mail

But When I send the contact form on php using ajax call on same page for multiple form, I do not get the data by mail.

Now, my confusion is that how to send the data by mail using ajax.

right now, I am sharing the source code as I have done in my functionality.

Hope!! I will get the solution.

index.php

    <!DOCTYPE html>
    <!--  This site was created in Webflow. http://www.webflow.com  -->
    <!--  Last Published: Wed Jul 18 2018 07:29:42 GMT+0000 (UTC)  -->
    <html data-wf-page="5b43680820a14a0ddeaf82d3" data-wf-site="5b43680820a14adf17af82d2">
    <head>
      <meta charset="utf-8">
      <title>Montreal</title>
      <meta content="width=device-width, initial-scale=1" name="viewport">
      <meta content="Webflow" name="generator">
      <style>.w-form-formrecaptcha {   margin-bottom: 8px; }</style>
      <link href="css/normalize.css" rel="stylesheet" type="text/css">
      <link href="css/webflow.css" rel="stylesheet" type="text/css">
      <link href="css/app-velocity-montreal.webflow.css" rel="stylesheet" type="text/css">
      <script src="https://ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js" type="text/javascript"></script>
      <script type="text/javascript">WebFont.load({  google: {    families: ["Heebo:100,300,regular,500,700,800,900","Sriracha:regular"]  }});</script>
      <!-- [if lt IE 9]><script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js" type="text/javascript"></script><![endif] -->
      <script type="text/javascript">!function(o,c){var n=c.documentElement,t=" w-mod-";n.className+=t+"js",("ontouchstart"in o||o.DocumentTouch&&c instanceof DocumentTouch)&&(n.className+=t+"touch")}(window,document);</script>
      <link href="https://daks2k3a4ib2z.cloudfront.net/img/favicon.ico" rel="shortcut icon" type="image/x-icon">
      <link href="https://daks2k3a4ib2z.cloudfront.net/img/webclip.png" rel="apple-touch-icon">
      <!--  Global site tag (gtag.js) - Google Analytics  -->
      <script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-54050564-1"></script>
      <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'UA-54050564-1');
    </script>
      <style>
    .sticky     { position: fixed; top: 0; background: rgba(255, 255, 255, 0.85); }
    .w-slider-dot { width: 10px; height: 10px; background-color: rgba(152, 168, 185, 0.54); margin: 0 4.5px .5em; }
    .w-slider-dot.w-active { background-color: #00beff; height: 15px; border-radius: 8px !important; }
    .w-slider-nav   { bottom: -3em; padding: 0px; }
    .client-blue-bg:after { content: ""; position: absolute; border-left: 38px solid #e5f8ff; border-top: 26px solid transparent; border-bottom: 0px solid transparent; right: -5.2em; width: 36.02px; height: 0; top: 0;}
    .client-purple-bg:before { content: ""; position: absolute; border-right: 38px solid #f9fafe; border-top: 26px solid transparent; border-bottom: 0px solid transparent; left: -5.2em; width: 36.02px; height: 0; top: 0; }
    .navbar.sticky { min-height: 60px;}
    .navbar.sticky a.brand { padding-top: 15px; padding-bottom: 13px; }
    .navbar.sticky nav a { padding-top: 19px; padding-bottom: 17px; }
    .navbar.sticky .menu-button { padding-top: 10px; padding-bottom: 10px; }
    .software-freelancer-block a { text-decoration: none; }
    .w-slider-arrow-left, .w-slider-arrow-right { color: rgba(152, 168, 185, 0.54); width: 40px; }
    .w-slider-arrow-left:hover, .w-slider-arrow-right:hover { color: #00beff; }
    @media only screen and (min-width: 1200px) {
        .wrapper { max-width: 1044px; }
    }
    @media (min-width: 992px) and (max-width: 1199px) {
        .banner { background-size: 50% auto; }
      .ux-wireframe-img { height: 205px; }
      .w-nav-overlay                        { top: 80px; z-index: 99 !important;}
      .w-slider-nav                         { bottom: -5em; }
      .right-arrow                          { right: -28px; }
      .left-arrow                               { left: -40px; }
    }
    @media (min-width: 768px) and (max-width: 991px) {
        .w-nav-overlay                      { top: 80px; z-index: 99 !important;}
        .right-arrow                            { right: -20px; font-size: 30px; }
        .left-arrow                             { left: -25px; font-size: 30px; }
    }
    @media only screen and (max-width: 767px) {
        .client-purple-bg:before    { display: none; }
      .client-blue-bg:after         { display: none; }
      .w-nav-overlay                        { top: 80px; z-index: 99 !important;}
      .w-slider-nav                         { bottom: -5em; }
    }
    @media only screen and (max-width: 800px) {
        .w-nav-button.w--open { background-color: transparent;}
      .w--nav-menu-open         { background-color: #00beff; background-image: none; }
    }
    span.error {
      color: #e7040f;
      margin: 10px;
      display: block;
    }
    span.success {
      color: #008000;
      margin: 10px;
      display: block;
    }
    #loader {
      width: 50px;
      height: 50px;
      margin: 10px;
      display: block;
    }
    .w-form-done {
      color: #008000;
    }
    </style>
    <!-- include Google hosted jQuery Library -->

    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    <script>
    $(function() {
       $("button").click(function() {
          var formID = $(this).closest('form').attr('id');
          var formData = $("#"+formID).serialize();
          var formid = "#"+formID;
          if($("#"+formID)[0].checkValidity()) {
           $.ajax({
            url: "contact_form_mail.php",
            dataType: "json",
            data: formData,
            success: function( data ) {
               // Handle success here
               if(data.fname == 'form1') {
                 var res = $.parseJSON(data);
            if (res.result === true) {

            }
                   } else if(data.fname == 'form2') {
                     var res = $.parseJSON(data);
            if (res.result === true) {

            }
                   }

            },
            error: function(e) {
              // Handle error here
              console.log(e);
            },
            timeout: 30000
          });
         } else {
          alert("Please enter name and message");
         }
       });
    });
    </script>
    </head>
    <body>
      <div class="modal-wrapper" data-ix="model-interaction">
        <div class="contact-wrapper w-clearfix"><a href="#" class="close-model w-inline-block" data-ix="close-lmodel-interaction"><img src="images/form-close-btn_1form-close-btn.png" class="image-25"></a>
          <div class="div-block-2 form-left w-hidden-small w-hidden-tiny"><img src="images/contact-form-img.svg" class="image-26"></div>
          <div class="form-right">
            <h1 class="heading-22">Contact Us</h1>
            <div class="w-form">
              <form id="form1" name="ContactForm" method="post" enctype="multipart/form-data" action="">
                <ul class="msgBox"></ul>
                <span class="error" style="display:none"> Please Enter Valid Data! </span>
                <input type="hidden" name="fname" value="form1">
                <input type="text" class="text-field fname w-input" maxlength="256" name="yourname" data-name="YourName" placeholder="Your Name*" id="yourname" required="">
                <input type="text" class="text-field-2 w-input" maxlength="256" name="email" data-name="Email" placeholder="Email Address*" id="email" required="">
                <input type="text" class="text-field-3 w-input" maxlength="256" name="subject" data-name="subject" placeholder="Subject*" id="subject" required="">
                <textarea id="comments" name="comments" placeholder="Message*" maxlength="5000" data-name="message" required="" class="textarea w-input"></textarea>
              <!--  <input type="submit" name="submit" value="Submit" id="submit1" data-wait="Please wait..." class="submit-button w-button">-->
                <button type="button">Submit</button>
                <div id="loader" style="display:none;"><img src="images/loader-img.gif" /></div>
                <div class="w-form-done" style="width:100%; height:100%; display:none;">
                   <div>Thank you! Your submission has been received!</div>
                 </div>
                <div class="w-form-fail" id="w-form-fail" style="width:100%; height:100%; display:none;">
                   <div>Oops! Something went wrong while submitting the form.</div>
                 </div>
              </form>
            </div>
          </div>
        </div>
      </div>
      <div class="get-quote-wrapper" data-ix="get-quote-model-interction">
        <div class="contact-wrapper get-quote-form-wrapper w-clearfix"><a href="#" class="close-model close-get-model w-inline-block" data-ix="close-lmodel-interaction"><img src="images/form-close-btn_1form-close-btn.png" class="image-25" data-ix="close-get-quote-lmodel-interaction"></a>
          <div class="form-left w-hidden-small w-hidden-tiny"><img src="images/get-quote-bg.svg" class="image-27"></div>
          <div class="form-right">
            <h1 class="heading-22 get-quote-heading">Get a quote within 48 hours</h1>
            <div class="w-form">
             <form id="form2" name="ContactForm" method="post" enctype="multipart/form-data" action="">
               <ul class="msgBox"></ul>
                <span class="error" style="display:none"> Please Enter Valid Data! </span>
                <input type="hidden" name="fname" value="form2">
                <input type="text" class="text-field fname get-fname w-input" maxlength="256" name="yourname" data-name="Your Name" placeholder="Your Name*" id="yourname" required="">
                <input type="text" class="text-field-2 get-email w-input" maxlength="256" name="email" data-name="Email" placeholder="Email Address*" id="email" required="">
                <input type="text" class="text-field-3 get-phone w-input" maxlength="256" name="phoneno" data-name="Phone Number" placeholder="Phone number*" id="phoneno" required="">
                <textarea id="comments" name="comments" placeholder="How can we help you? *" maxlength="5000" data-name="Message" required="" class="textarea get-msg w-input"></textarea>
              <!--  <input type="submit" name="submit" value="Submit" id="submit2" data-wait="Please wait..." class="submit-button w-button"> -->
                <button type="button">Submit</button>
                <div id="loader" style="display:none;"><img src="images/loader-img.gif" /></div>
                <div class="w-form-done" style="width:100%; height:100%; display:none;">
                   <div>Thank you! Your submission has been received!</div>
                 </div>
                <div class="w-form-fail" id="w-form-fail" style="width:100%; height:100%; display:none;">
                   <div>Oops! Something went wrong while submitting the form.</div>
                 </div>
              </form>
            </div>
          </div>
        </div>
      </div>
      <div class="let-talk-wrapper" data-ix="let-talk-model-interction">
        <div class="contact-wrapper let-talk-form-wrapper w-clearfix"><a href="#" class="close-model close-let-model w-inline-block" data-ix="close-let-talk-lmodel-interaction"><img src="images/form-close-btn_1form-close-btn.png" class="image-25" data-ix="close-get-quote-lmodel-interaction"></a>
          <div class="form-left w-hidden-small w-hidden-tiny"><img src="images/lets-talk-img.svg" class="image-28"></div>
          <div class="form-right">
            <h1 class="heading-22 let-talk-heading">Say Hello!</h1>
            <div class="w-form">
              <form id="form2" name="ContactForm" method="post" enctype="multipart/form-data" action="">
                <ul class="msgBox"></ul>
                 <span class="error" style="display:none"> Please Enter Valid Data! </span>
                 <input type="hidden" name="fname" value="form2">
                 <input type="text" class="text-field fname get-fname w-input" maxlength="256" name="yourname" data-name="Your Name" placeholder="Your Name*" id="yourname" required="">
                 <input type="text" class="text-field-2 get-email w-input" maxlength="256" name="email" data-name="Email" placeholder="Email Address*" id="email" required="">
                 <input type="text" class="text-field-3 get-phone w-input" maxlength="256" name="phoneno" data-name="Phone Number" placeholder="Phone number*" id="phoneno" required="">
                 <textarea id="comments" name="comments" placeholder="How can we help you? *" maxlength="5000" data-name="Message" required="" class="textarea get-msg w-input"></textarea>
               <!--  <input type="submit" name="submit" value="Submit" id="submit2" data-wait="Please wait..." class="submit-button w-button"> -->
                 <button type="button">Submit</button>
                 <div id="loader" style="display:none;"><img src="images/loader-img.gif" /></div>
                 <div class="w-form-done" style="width:100%; height:100%; display:none;">
                    <div>Thank you! Your submission has been received!</div>
                  </div>
                 <div class="w-form-fail" id="w-form-fail" style="width:100%; height:100%; display:none;">
                    <div>Oops! Something went wrong while submitting the form.</div>
                  </div>
               </form>
            </div>
          </div>
        </div>
      </div>
      
    </body>
    </html>

contact_form_mail.php

<?php
error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Toronto');
require_once("class.phpmailer.php");
require_once("class.smtp.php"); // note, this is optional - gets called from main class if not already loaded

if(isset($_POST['email'])) {

    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "Priyanka.M@simformsolutions.com";
    $email_subject = "Contact Form Details";

    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.<br /><br />";
        echo $error."<br /><br />";
        echo "Please go back and fix these errors.<br /><br />";
        die();
    }

    // validation expected data exists
    if(!isset($_POST['yourname']) ||
        !isset($_POST['email']) ||
        !isset($_POST['subject']) ||
        !isset($_POST['comments'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');
    }

    $first_name = $_POST['yourname']; // required
    $email_from = $_POST['email']; // required
    $subject    = $_POST['subject']; // required
    $comments   = $_POST['comments']; // required
    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
    $string_exp = "/^[A-Za-z .'-]+$/";

  if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'The Name you entered does not appear to be valid.<br />';
  }

  if(strlen($comments) < 2) {
    $error_message .= 'The Comments you entered do not appear to be valid.<br />';
  }

  if(strlen($error_message) > 0) {
    died($error_message);
  }

    $email_message = "Contact Form details below.

"."<br><br>";

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

    $email_message .= "Your Name: ".clean_string($first_name)."
"."<br>";
    $email_message .= "Email: ".clean_string($email_from)."
"."<br>";
    $email_message .= "Subject: ".clean_string($subject)."
"."<br>";
    $email_message .= "Comments: ".clean_string($comments)."
"."<br>";
  
    $mail             = new PHPMailer();
    $body             = $output_email_msg;
    $mail->IsSMTP(); // telling the class to use SMTP

    //$mail->SMTPSecure = 'tls';
    //$mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)
                                               // 1 = errors and messages
                                               // 2 = messages only


    $mail->Host="smtp.sendgrid.net";
    //$mail->Host       = "smtp.office365.com"; // SMTP server
    $mail->Username="open_source_simform";
    $mail->Password="open_source_simform57";


    $mail->SMTPAuth   = true;                  // enable SMTP authentication
    $mail->Port       = 587;                    // set the SMTP port for the GMAIL server

    $mail->SetFrom($email_from, $first_name);

    $mail->AddReplyTo($email_from, $first_name);

    $mail->Subject    = "AppVelocity Contact Form Details";

    $mail->MsgHTML($body);

    $address = "priyanka.m@simformsolutions.com";
    $mail->AddAddress($address, "John Doe");

    $formData = $_REQUEST;
    if($formData['fname'] == 'form1') {
        if(!$mail->Send()) {
          echo "false";exit;
        } else {
          echo "true";exit;
        }
      } else if($formData['fname'] == 'form2') {
        if(!$mail->Send()) {
          echo "false";exit;
        } else {
          echo "true";exit;
        }
}
?>

</div>
dongpan2788
dongpan2788 -这不是我的事。错误日志如Object{readyState:4,getResponseHeader:getResponseHeader(),getAllResponseHeaders:getAllResponseHeaders(),setRequestHeader:setRequestHeader(),overrideMimeType:overrideMimeType(),statusCode:statusCode(),abort:abort(),state:state(),总是:always(),catch:catch(),â€|
2 年多之前 回复
dongxuxian1123
dongxuxian1123 除了这些,这些表单对我的代码起作用
2 年多之前 回复
doushi8186
doushi8186 嗯,第一种形式有一个表格字段“主题”,第二种形式不存在。并且你正在检查php中的主题if(!isset($_POST['yourname'])||!isset($_POST['email'])||!isset($_POST['subject'])||!isset($_POST['comments'])){
2 年多之前 回复
dqt20140129
dqt20140129 -现在,这里没有用于发送数据的提交按钮
2 年多之前 回复
dongpu9481
dongpu9481 添加方法:发布到你的ajax调用url:“contact_form_mail.php”,dataType:“json”,方法:“post”,data:formData,
2 年多之前 回复
dsour68888
dsour68888 我已经发送了单个表单的数据,但是当我尝试发送两个表单或多个表单的数据时,我无法获取数据
2 年多之前 回复
dte49889
dte49889 ---这不是真的...目前我想发送2表格的数据而不是我将为第三表格工作
2 年多之前 回复
drde3456
drde3456 您将数据作为get请求发送,并在php部分中访问$_POST
2 年多之前 回复
doumeitang572461
doumeitang572461 您的第三个表单是发送表单2的数据,因为表单ID是“form2”,而不是ajax请求正在触发。你错过了一个关闭}在PHP中
2 年多之前 回复
dounayan3643
dounayan3643 -我已经显示了代码。请检查并建议我
2 年多之前 回复
dongsicheng5262
dongsicheng5262 -我附上了index.php中提到的javascript代码。请建议我。
2 年多之前 回复
dsdqpdjpq16640651
dsdqpdjpq16640651 你使用相同的jquery/js脚本来触发ajax请求或不同的调用,如果你使用不同的调用,检查你是否在ajax请求上将电子邮件字段的名称设置为“email”
2 年多之前 回复
doulan8846
doulan8846 发布您的JavaScript代码。调试的其他步骤。index.php中的var_dump$_POST['email']来检查它是否已设置。
2 年多之前 回复
dqr3883
dqr3883 是的...我在一个页面上使用了不同的按钮来提交联系表格。
2 年多之前 回复
douyu2817
douyu2817 所有按钮点击都会触发ajax请求吗?
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐