无法通过AJAX/Jquery在HTML文件中获取PHP变量

无法通过AJAX/Jquery在HTML文件中获取PHP变量,php,jquery,html,ajax,Php,Jquery,Html,Ajax,我真正开始学习PHP/AJAX/Jquery。我在这个页面上尝试了hunijkah的代码,PHP文件返回:{“success”:true,“errors”:[]}在一个空白页面上替换当前页面。我收到了电子邮件。因此,我假设contact.php可以工作。我想知道如何在HTML文件中返回“success”,并在成功操作后在当前页面的表单下方写下答案。 在这张表格中,我使用了: <form action="contact.php" method="post" id="mail_form">


我真正开始学习PHP/AJAX/Jquery。我在这个页面上尝试了hunijkah的代码,PHP文件返回:
{“success”:true,“errors”:[]}
在一个空白页面上替换当前页面。我收到了电子邮件。因此,我假设contact.php可以工作。
我想知道如何在HTML文件中返回“success”,并在成功操作后在当前页面的表单下方写下答案。
在这张表格中,我使用了:

<form action="contact.php" method="post" id="mail_form">
  <fieldset>
    <legend>Coordonnées personnelles :</legend>
    <p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Prénom *" required name="firstname" maxlength="50"></p>
    <p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Nom *" required name="lastname" maxlength="50"></p>
    <p><input class="w3-input w3-padding-16 w3-border" type="email" placeholder="Email *" required name="email"></p>
    <p><input class="w3-input w3-padding-16 w3-border" type="tel" placeholder="+681 12 34 56 *" required name="usrtel"></p>
  </fieldset>
  <fieldset>
    <legend>Informations :</legend>
    <p><input class="w3-input w3-padding-16 w3-border" type="number" placeholder="Combien de personne(s) *" required name="people" min="1" max="100"></p>
    <p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Message \ Besoins particuliers *" required name="message"></p>
  </fieldset>
  <p>* Champs obligatoires</p>
  <br>
  <div class="g-recaptcha" data-theme="dark" data-sitekey="6LdMKTcUAAAAABNdlU76EOu6W3Wv61T7uKGM9HwB"></div>
  <p>Souhaitez-vous une copie de votre message ? 
  <input type="radio" id="rep_oui" name="copie" value="oui" checked><label for="rep_oui">Oui</label>
  <input type="radio" id="rep_non" name="copie" value="non"><label for="rep_non">Non</label></p>
  <p id="error" class="w3-red w3-xlarge w3-center"></p>
  <p><button class="w3-button w3-light-grey w3-block" type="submit" name="submit">ENVOYER LE MESSAGE</button></p>
  <p><button class="w3-button w3-light-grey w3-block" type="reset">EFFACER</button></p>
</form> 

协调人:

资料:

*义务冠军


你能给我复述一下留言吗? 是的 非

外交使节

埃法克

在HTML文件中,我将此脚本放在head标记之间:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> // 2.1.3 -> 3.2.1
//2.1.3->3.2.1
我文件底部的脚本:

<script>
  $('#mail_form').on('submit', function(event)
  {
    event.preventDefault();
    var dataIn = $(this).serialize(); //serialize turns the form data into a string that can be passed to contact.php. Try doing alert(dataIn); to see what it holds.
    $.post( "./contact.php" , dataIn )
    .done(function( dataOut )
    {
      //dataOut holds the response from contact.php. The response would be any html mail.php outputs. I typically echo out json encoded arrays as responses that you can parse here in the jQuery.
      var finalArray = JASON.parse ( dataOut );
      if ((finalArray['success'] == true) && (finalArray['error1'] == false) && (finalArray['error2'] == false))//Check if it was successfull.
      {  
        $("#mail_form").html("<p class='w3-xxlarge w3-center w3-tag'><strong>Votre message a bien été envoyé !</strong></p>");
      }
      else //there were errors
      {
        if (finalArray['error1'] == true)
        {
          // message not sent
          $('#error').html("<p class='w3-xxlarge w3-center w3-tag'><strong>L'envoi du mail a échoué, veuillez réessayer, s'il vous plaît.</strong></p>");
        }
        else if (finalArray['error2'] == true)
        {
          // one of 7 variables (at least) is empty ...
          $('#error').html("<p class='w3-xxlarge w3-center w3-tag'><strong>Vérifiez que tous les champs soient bien remplis et que l'email soit sans erreur.</strong></p>");
        }
        else
        {
          // recaptcha is false
          $('#error').html("<p class='w3-xxlarge w3-center w3-tag'><strong>Problème d'authentification par le Recaptcha</strong></p>");
        };
      };
    });
      return false; //Make sure you do this or it will submit the form and redirect
  });
</script>

$('mail#u form')。在('submit',函数(事件)
{
event.preventDefault();
var dataIn=$(this).serialize();//serialize将表单数据转换为可传递给contact.php的字符串。请尝试执行警报(dataIn);以查看它包含的内容。
$.post(“./contact.php”,数据输入)
.完成(功能(数据输出)
{
//dataOut保存contact.php的响应。响应将是任何html mail.php输出。我通常将json编码的数组作为响应进行回显,您可以在jQuery中解析这些响应。
var finalArray=JASON.parse(dataOut);
if((finalArray['success']==true)&&(finalArray['error1']==false)&&(finalArray['error2']==false))//检查它是否成功。
{  
$(“#邮件表单”).html(

Votre message a bienétéemissioné!

”; } 否则就会出错 { if(finalArray['error1']==true) { //消息未发送 $(“#error”).html(

L'envoi du mail aéchoué,veuillez réessayer,s'il vous plaît.”; } else if(finalArray['error2']==true) { //7个变量中至少有一个为空。。。 $(“#error”).html(

Vérifiez que tous les champs soient bien remplis et que l'email soit sans erreur.”; } 其他的 { //雷帕查是假的 HTML(“P类=‘W3-XXWORD W3中心W3标签’>强> Prl LeRAPTCHA < /强>

”; }; }; }); return false;//确保执行此操作,否则它将提交表单并重定向 });
我看不出我的错误。这是完全相同的代码,我想知道出了什么问题。也许有人能帮我,因为几天后我遇到了麻烦。 我可以在HTML文件中使用测试来确保PHP文件传递成功变量吗

PS:PHP文件

<?php

    $success = true;
    $error1 = false;
    $error2 = false;

     // ReCAPTCHA
     // grab recaptcha library
     require_once "recaptchalib.php";

     // foreach ($_POST as $key => $value) {
     // echo '<p><strong>' . $key.':</strong> '.$value.'</p>';
     // }

     // your secret key
     $secret = "***_***";

     // empty response
     $response = null;

     // check secret key
     $reCaptcha = new ReCaptcha($secret);

     // if submitted check response
     if ($_POST["g-recaptcha-response"]) {
          $response = $reCaptcha->verifyResponse(
          $_SERVER["REMOTE_ADDR"],
          $_POST["g-recaptcha-response"]
          );
     }

/*
    ********************************************************************************************
    CONFIGURATION
    ********************************************************************************************
*/

// destinataire est votre adresse mail. Pour envoyer à plusieurs à la fois, séparez-les par une virgule
$destinataire = '***@***.**,***@***.**';

// copie ? (envoie une copie au visiteur)
// $copie = 'oui';

// objet du message
$objet = 'Contact depuis le site ***';

// Action du formulaire (si votre page a des paramètres dans l'URL)
// si cette page est index.php?page=contact alors mettez index.php?page=contact
// sinon, laissez vide
$form_action = '';

/*
    ********************************************************************************************
    FIN DE LA CONFIGURATION
    ********************************************************************************************
*/

/*
 * cette fonction sert à nettoyer et enregistrer un texte
 */
function Rec($text)
{
    $text = htmlspecialchars(trim($text), ENT_QUOTES);
    if (1 === get_magic_quotes_gpc())
    {
        $text = stripslashes($text);
    }

    $text = nl2br($text);
    return $text;
};

/*
 * Cette fonction sert à vérifier la syntaxe d'un email
 */
function IsEmail($email)
{
    $value = preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $email);
    return (($value === 0) || ($value === false)) ? false : true;
}


// formulaire envoyé, on récupère tous les champs.
    $firstnameint     = (isset($_POST['firstname']))     ? Rec($_POST['firstname'])        : '';
    $lastnameint      = (isset($_POST['lastname']))      ? Rec($_POST['lastname'])         : '';
    $email            = (isset($_POST['email']))         ? Rec($_POST['email'])            : '';
    $usrtelint        = (isset($_POST['usrtel']))        ? Rec($_POST['usrtel'])           : '';
    $people           = (isset($_POST['people']))        ? Rec($_POST['people'])           : '';
    $messageint       = (isset($_POST['message']))       ? Rec($_POST['message'])          : '';
    $copieint         = (isset($_POST['copie']))         ? Rec($_POST['copie'])            : '';

// traitement du numéro de téléphone et aux variables
    $firstname = htmlspecialchars($firstnameint);
    $lastname = htmlspecialchars($lastnameint);
    $usrtel = htmlspecialchars($usrtelint);
    $message = htmlspecialchars($messageint);
    $copie = htmlspecialchars($copieint);

// traitement du nombre de convives
    $people = sprintf("%d",$_POST['people']); // ici le nombre sera un entier
    $people = abs($people); // $people sera positif ou nul = valeur absolue (évite les âges négatifs !)
    $people = intval($people); // renvoie aussi une valeur entière
    if (is_numeric($people)) // n'effectue que si $people est numérique
    {   
    } else {
        $people='0';
    }
    if ($people >= 1 && $people <= 100) // n'effectue que si $usrtel est borné
    {
    } else {
        $people='0';
    }

// On va vérifier les variables et l'email ...
     $email = (IsEmail($email)) ? $email : ''; // soit l'email est vide si erroné, soit il vaut l'email entré

if (isset($_POST['submit']))
{
    if ($response != null && $response->success)
    {    
        if (($firstname != '') && ($lastname != '') && ($email != '') && ($usrtel != '') && ($people != '') && ($message != '') && ($copie != ''))
        {
            // les 6 variables sont remplies, on génère puis envoie le mail
            $headers  = 'MIME-Version: 1.0' . "\n";
            $headers .= 'From:'.$firstname.' '.$lastname.' <'.$email.'>' . "\n" .
            $headers .= 'Reply-To:'.$email. "\n" .
            $headers .= 'Content-Type: text/html; charset="utf-8"; DelSp="Yes"; format=flowed '."\n" .
            $headers .= 'X-Mailer:PHP/'.phpversion().
            $headers .= 'Content-Transfer-Encoding: 7bit'." \r\n" ;

            // envoyer une copie au visiteur ?
            if ($copie == 'oui')
            {
                $cible = $destinataire.';'.$email;
            }
            else
            {
                $cible = $destinataire;
            };

            // Remplacement de certains caractères spéciaux
            $message = str_replace("&#039;","'",$message);
            $message = str_replace("&#8217;","'",$message);
            $message = str_replace("&quot;",'"',$message);
            $message = str_replace('<br>','',$message);
            $message = str_replace('<br />','',$message);
            $message = str_replace("&lt;","<",$message);
            $message = str_replace("&gt;",">",$message);
            $message = str_replace("&amp;","&",$message);

            // formatage du corps de l'email
            $msg = '<div style="width: 100%; text-align: left; color: #00002b; font-weight: bold"> Message de '.$firstname.' '.
            $lastname.'<br />E-mail : '.$email.' et numéro de téléphone : '.$usrtel.'<br /> nombre de personne(s) : '.$people.
            '<br /> Message : '.$message.'</div>';

            // Envoi du mail
            $num_emails = 0;
            $tmp = explode(';', $cible);          
            foreach($tmp as $email_destinataire)
            {
                if (mail($email_destinataire, $objet, $msg, $headers))
                $num_emails++;
            }

            if ((($copie == 'oui') && ($num_emails == 2)) || (($copie == 'non') && ($num_emails == 1)))
            {
                // message sent
                // Votre message a bien été envoyé !
            }
            else
            {
                // message not sent
                // L'envoi du mail a échoué, veuillez réessayer, s'il vous plaît
                $error1 = true;
            };               
        }
        else
        {
            // one of 7 variables (at least) is empty ...
            // Vérifiez que tous les champs soient bien remplis et que l'email soit sans erreur
            $error2 = true;
        };                
    }
    else
    {
        // recaptcha is false
        // Problème d'authentification par le Recaptcha
        $success = false;
    };
}; // fin du if (!isset($_POST['envoi']))

        $array['success'] = $success;
        $array['error1'] = $error1;
        $array['error2'] = $error2;
        $finalArray=json_encode($array);
        echo $finalArray;
?> 

您编写的代码缺少一个)括号…您必须在浏览器中的console.log中看到JSON.parse之后返回的内容…我附加了缺少括号的代码。
PS:对于Jquery,现在它在3.2版本上……我建议升级到当前版本,而不是继续使用版本2,但这不会影响您的代码

          $('#mail_form').on('submit', function()
          {
            var dataIn = $(this).serialize(); //serialize turns the form data into a string that can be passed to contact.php. Try doing alert(dataIn); to see what it holds.
            $.post("./contact.php", dataIn )
            .done(function( dataOut )
            {
              //dataOut holds the response from contact.php. The response would be any html mail.php outputs. I typically echo out json encoded arrays as responses that you can parse here in the jQuery.
              var myArray = JSON.parse(dataOut);
              console.log(myArray);
              if (myArray['success'] == true) //Check if it was successfull.
              {
                $("#mail_form").html("Congrats! We just e-mailed you!");
              }
              else //there were errors
              { 
                $('#error').html(""); //Clear error span
                $.each(myArray['errors'], function(i)
                { 
                  $('#error').append(myArray['errors'][i] + "<br>");
                });//------->HERE WAS MISSING A ); 
              };
            });
              return false; //Make sure you do this or it will submit the form and redirect
          });   
json如下所示:

  {"status":"success","records":[{"recid":"1","rowid":9,"utente":"Andrea","mese":"Aprile","orePermesso":"8"},{"recid":"2","rowid":8,"utente":"andrea","mese":"Gennaio","orePermesso":"8"}],"totaleRisultati":2}
因此,您的代码像使用数组一样使用success和error,因为我从您的代码中假设errors是一个数组($。每个(myArray['errors'])可能是:

       $arrayErrori[] = array('1'=>'error1','2'=>'error2');
       $array['succes'] = true;
       $array['errors'] = $arrayErrori;
       $finalArray=json_encode($array);
       print $finalArray;
json看起来是这样的……但请记住,“真”可以像字符串一样识别,必须在路上看到

    {"succes":true,"errors":[{"1":"error1","2":"error2"}]}
好的,现在我看到了你的php。你的错误是,你正在解析一个刚刚在服务器端解析的对象,你的json是正确的。错误如下:

       var myArray = JSON.parse( dataOut );
dataOut是json格式的,您不需要重新分析。所以

            var myArray = dataOut //Don't need to reparse again
一个ajax调用和php的示例

        $.ajax({
          type: "POST",
          url: "MNYLINKPHPTOCALL JSON",
          dataType: "JSON",
          data:{},
          success:function(data){   
                console.log(data);  
                console.log(data.success);
                console.log(data.errors);
                console.log(data.errors[0]);
                console.log(data.errors[1]);
          },
          error:function(data){
            alert('Chiamata Fallita');
          }
        });
以及来自PHP的JSON

$risultatiErrors= array("prova","prova2");      
$output_array['success'] = true;
$output_array['errors'] = $risultatiErrors;
$final = json_encode($output_array);//<---------yOU ARE JUST ENCODING HERE
echo $final;    
$risultatiErrors=数组(“prova”、“prova2”);
$output_array['success']=true;
$output_array['errors']=$risultatiErrors;

$final=json_encode($output_数组)//Javascript控制台中是否有错误?我敢打赌,除了JSON之外,
contact.php
还会输出一些HTML。没有什么是不可能的!您已经采取了基本的调试步骤了吗?检查控制台输出。在检查器的“网络”选项卡中检查请求返回的内容。添加
console.log
调用,在处理数据时调用所有调用。哦,天哪,你甚至可以在代码中使用断点并检查数据。你能想象吗?我打赌你还在提交表单,把它改成
$('#mail_form')。在('submit',function(event){event.preventDefault();
感谢您的帮助。我修复了丢失的braket和Jquery版本。我找到了console.log,现在它返回:SyntaxError:JSON.parse:JSON数据第2行第1列的意外数据结尾。我尝试使用()但我不知道如何正确使用它。多亏了你,我取得了一些进展。我修改了html和php文件,并将其重新放在了我的原始邮件中。你的解释非常清楚,我只需要时间来消化它们:D.
此外,我还看到我的html页面被修改,我想要修改(表单消失,而出现确认消息)但是没有发送更多的电子邮件。在我没有检查Recaptcha就发送了一条消息之后,html页面不再被修改。现在,我收到了电子邮件,但是在提交之后,我到达了这个页面(mysite/contact.php),并且带有{“success”:true,“errors”:[{“error1”:“error2”:“}]}消息。现在,我将尝试理解并改进我的Ajax函数代码。非常感谢您的帮助!我已经发布了我的上一个php文件和脚本JSON,我不能再提交了,我想是因为我错过了HTML文件中的一些内容。我将返回到您的Ajax函数。再次感谢Spizzi对您的所有贡献。
$risultatiErrors= array("prova","prova2");      
$output_array['success'] = true;
$output_array['errors'] = $risultatiErrors;
$final = json_encode($output_array);//<---------yOU ARE JUST ENCODING HERE
echo $final;