简体   繁体   English

为什么我的Ajax请求无法与post方法一起使用?

[英]Why my Ajax request isn't working with post method?

I come to ask for help because I have a problem that persists for three days and I can't understand where the problem is. 我来寻求帮助,因为我的问题持续了三天,我无法理解问题所在。 I have a form on an HTML page here : 我在HTML页面上有一个表单:

<form id="contactformpage">
<div class="messages"></div>
            <div class="form-group row">
              <label for="societepage" class="col-sm-6 col-form-label">Société</label>
              <div class="col-sm-6 champ">
              <input type="text" name="societe" class="form-control" id="societepage"  placeholder="Nom de la société" aria-describedby="indicsocietepage">
              <small id="indicsociete" class="form-text text-muted"> * Obligatoire </small>
              </div>
            </div>
            <div class="form-group row">
              <label for="adressepage" class="col-sm-6 col-form-label" >Adresse</label>
              <div class="col-sm-6 champ">
              <input type="text" name="adresse" class="form-control" id="adressepage"  placeholder="Adresse">
              </div>
            </div>
            <div class="form-group row">
              <label for="codepostaletvillepage" class="col-sm-6 col-form-label" >Code postal & ville</label>
              <div class="col-sm-6 champ">
              <input type="text" class="form-control" name="codepostaletville" id="codepostaletvillepage"  placeholder="Code postal & ville">
              </div>
            </div>
            <div class="form-group row">
              <label for="contactpage" class="col-sm-6 col-form-label">Nom du contact</label>
              <div class="col-sm-6 champ">
              <input type="text" class="form-control" name="contact" id="contactpage"  placeholder="Nom du contact">
              </div>
            </div>
            <div class="form-group row">
              <label for="telephonepage" class="col-sm-6 col-form-label">Téléphone</label>
              <div class="col-sm-6 champ">
              <input type="text" class="form-control" name="téléphone" id="telephonepage" placeholder="Numéro de téléphone" aria-describedby="indictelephonepage">
              <small id="indictelephonepage" class="form-text text-muted"> * Obligatoire </small>
              </div>
            </div>
            <div class="form-group row">
              <label for="mailpage" class="col-sm-6 col-form-label">Adresse mail</label>
              <div class="col-sm-6 champ">
              <input type="email" class="form-control" name="mail" id="mailpage" placeholder="Entrez votre adresse mail" aria-describedby="indicmailpage">
              <small id="indicmailpage" class="form-text text-muted"> * Obligatoire </small>
              </div>
            </div>
            <div class="form-group row">
              <label class="col-sm-6 col-form-label" for="selecmarque" aria-describedby="indicmarquepage"> Marque du véhicule </label>
              <div class="col-sm-6 champ">
              <select class="form-control" name="marque" style="height:20px;padding-bottom:0;padding-top:1;" onchange="generechoixmodele('selecmarque','apreschoixmarquepage','apreschoixmodelepage','nommodelepage','choixmodelepage','choixtypepage');" id="selecmarque">
                <option selected> Séléctionnez </option>
              </select>
              </div>
            </div>
            <div class="form-group row"  id="apreschoixmarquepage" style="display:none;"> <!-- Liste déroulante qui apparait après le choix de la marque -->
              <label class="col-sm-6 col-form-label" for="apreschoixmarquepage" aria-describedby="indicmarque" id="nommodelepage"></label>
              <div class="col-sm-6 champ">
              <select class="form-control" name="modele" style="height:20px;padding-bottom:0;padding-top:1;" id="choixmodelepage" onchange="generechoixtype('selecmarque','choixmodelepage','apreschoixmodelepage','nomtypepage','choixtypepage');">
              </select>
              </div>
            </div>
            <div class="form-group row" id="apreschoixmodelepage" style="display:none;"> <!-- Liste déroulante qui apparait après le choix du modèle -->
              <label class="col-sm-6 col-form-label" for="apreschoixmodelepage" aria-describedby="indicmarque" id="nomtypepage"></label>
              <div class="col-sm-6 champ">
              <select class="form-control" name="type" style="height:20px;padding-bottom:0;padding-top:1;" id="choixtypepage">
              </select>
              </div>
            </div>
              <p> Je souhaite recevoir les catalogues suivants (dynamique)</p>
              <div id="choixcataloguepage">
              </div>
              <div class="form-group row">
                <label class="col-sm-6 col-form-label" for="commentairepage">Commentaire</label>
                <div class="col-sm-6 champ">
                  <textarea class="form-control" name="commentaire" id="commentairepage" rows="1"></textarea>
                </div>
              </div>
              <div class="form-group row">
                <label for="mail" class="col-sm-6 col-form-label">Captcha</label>
                <div class="col-sm-6 champ">
                  <h6> Captcha à rajouter après </h6>
                </div>
              </div>
            <input type="submit" class="btn" id="submitpage">
          </form>

And when I click on the button of this form, I send the data entered by the user thanks to an Ajax request on a php page: 当我单击此表单的按钮时,由于在php页面上的Ajax请求,我发送了用户输入的数据:

$(document).ready(function(){

$("#submitpage").click(function(e){
    e.preventDefault();

    $.ajax({
        type: "POST",
        url: 'sendform.php',
        dataType: "JSON",
        data: {
            societe : $("#societepage").val(),
            adresse : $("#adressepage").val(),
            codepostaletville : $("#codepostaletvillepage").val(),
            contact : $("#contactpage").val(),
            telephone : $("#telephonepage").val(),
            mail : $("#mailpage").val(),
            marqueclient : $("#selecmarque").val(),
            modeleclient : $("#choixmodelepage").val(),
            typeclient : $("#choixtypepage").val(),
            commentaire : $("#commentairepage").val()
        },
        success: function (data)
        {
            // data = JSON object that contact.php returns

            // we recieve the type of the message: success x danger and apply it to the
            var messageAlert = 'alert-' + data.type;
            var messageText = data.message;

            // let's compose Bootstrap alert box HTML
            var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';

            // If we have messageAlert and messageText
            if (messageAlert && messageText) {
                // inject the alert to .messages div in our form
                $('#contactformpage').find('.messages').html(alertBox);
                // empty the form
                $('#contactformpage')[0].reset();
            }
        }
    })
});

}); });

I know it's possible to do $(this).serialize() for forms directly but I'd like to do that already. 我知道可以直接为表单执行$(this).serialize(),但我已经想这样做了。 Here is the PHP script in question, so I send my data with the POST method, the problem is that this script tells me all the time "Form is empty" which means that the data was not sent with POST (since $ _POST is empty). 这是有问题的PHP脚本,因此我使用POST方法发送数据,问题在于此脚本一直告诉我“ Form is empty”,这意味着数据不是通过POST发送的(因为$ _POST为空)。 And when I try to make an echo ($_SERVER['HTTP_X_REQUESTED_WITH']), the php script returns an empty string, which means that the Ajax request was not made. 当我尝试进行回显($ _SERVER ['HTTP_X_REQUESTED_WITH'])时,php脚本返回一个空字符串,这意味着未发出Ajax请求。

    <?php
/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
AND ALSO SMTP TO SEND THE EMAILS
*/
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer/PHPMailer-master/src/Exception.php';
require 'PHPMailer/PHPMailer-master/src/SMTP.php';
require 'PHPMailer/PHPMailer-master/src/OAuth.php';
require 'PHPMailer/PHPMailer-master/src/POP3.php';
/*
*  CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$fromEmail = 'lyes.tifoun@hotmail.fr';
$fromName = 'Demo contact form';

// an email address that will receive the email with the output of the form
$sendToEmail = 'lyestfn@gmail.com';
$sendToName = 'Lyes Tifoun';
// subject of the email
$subject = 'New message from contact form';

// smtp credentials and server

$smtpHost = 'smtp.gmail.com';
$smtpUsername = 'nom_utilisateur';
$smtpPassword = 'mdp';

$fields = array('societe' => 'Société', 'adresse' => 'Adresse', 'codepostaletville' => 'Code postal et ville', 'contact' => 'Nom du contact', 'téléphone' => 'Numéro de téléphone', 'mail' => 'Adresse mail', 'marque' => 'Marque du véhicule', 'modele' => 'Modèle du véhicule', 'type' => 'Type du véhicule', 'commentaire' => 'Commentaire');

$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';


$errorMessage = 'There was an error while submitting the form. Please try again later';


error_reporting(E_ALL & ~E_NOTICE);
try {
    if (count($_POST) == 0) {
        throw new \Exception('Form is empty');
    }

    $emailTextHtml = "<h1>You have a new message from your contact form</h1><hr>";
    $emailTextHtml .= "<table>";

    foreach ($_POST as $key => $value) {
        // If the field exists in the $fields array, include it in the email
        if (isset($fields[$key])) {
            $emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
        }
    }
    $emailTextHtml .= "</table><hr>";
    $emailTextHtml .= "<p>Have a nice day,<br>Best,<br>Ondrej</p>";

    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->SMTPDebug = 1;
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = 'tls';
    $mail->Host = gethostbyname($smtpHost);
    $mail->Port = 587;
    $mail->isHTML(true);
    $mail->SMTPOptions = array('ssl' => array('verify_peer' => false,'verify_peer_name' => false,'allow_self_signed' => true));
    $mail->Username = $smtpUsername;
    $mail->Password = $smtpPassword;
    $mail->setFrom($fromEmail, $fromName);
    $mail->addAddress($sendToEmail, $sendToName); // you can add more addresses by simply adding another line with $mail->addAddress();
    $mail->addReplyTo($from);




    $mail->Subject = $subject;
    $mail->Body = 'test';//$emailTextHtml;
    $mail->msgHTML($emailTextHtml); // this will also create a plain-text version of the HTML email, very handy


    $mail->Debugoutput = 'html';


    if (!$mail->send()) {
        throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
    }

    $responseArray = array('type' => 'success', 'message' => $okMessage);
} catch (\Exception $e) {
    // $responseArray = array('type' => 'danger', 'message' => $errorMessage);
    $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);
    header('Content-Type: application/json');

    echo $encoded;
}
// else just display the message
else {
    echo $responseArray['message'];
}

I would like to understand why my request doesn't work because I don't think I made any syntax or other errors. 我想了解为什么我的请求不起作用,因为我不认为自己犯了任何语法或其他错误。 Here is the script used for the JQuery library in my HTML file. 这是HTML文件中用于JQuery库的脚本。

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

And I use WAMPServer to run my site locally, I already did my research but could the problem come from there by chance? 我使用WAMPServer在本地运行我的站点,我已经进行了研究,但是问题可能出在这里吗? Thank you in advance 先感谢您

I come back to you to inform you that my data is finally sent with $_POST as shown by the network panel: 我再次通知您,我的数据最终通过$ _POST发送,如网络面板所示:

enter image description here 在此处输入图片说明

I've also made a var_dump($_SERVER) and the $_SERVER['HTTP_X_REQUESTED_WITH'] value is "XML HTTPREQUEST" which indicates that the Ajax request has been launched. 我还制作了一个var_dump($ _ SERVER),$ _ SERVER ['HTTP_X_REQUESTED_WITH']的值为“ XML HTTPREQUEST”,它指示已启动Ajax请求。 Now I have an other problem : I don't have a client-side response: currently the program seems to validate the condition if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') and I have an echo($encoded) in JSON format as shown below : 现在,我还有另一个问题:我没有客户端响应:目前,该程序似乎正在验证条件if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')并且我有JSON格式的echo($encoded) ,如下所示:

enter image description here 在此处输入图片说明

Therefore I should have a client-side response, which is not the case actually. 因此,我应该有一个客户端响应,实际上并非如此。

Thanks a lot for your responses and sorry for my bad english. 非常感谢您的回复,对于我的英语不好,我深表歉意。

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

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