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

时间:2019-07-23 14:28:29

标签: javascript php jquery ajax post

我来寻求帮助,因为我的问题持续了三天,我不知道问题出在哪里。我在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>

当我单击此表单的按钮时,由于在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();
            }
        }
    })
});

});

我知道可以直接为表单执行$(this).serialize(),但是我已经想这样做了。这是有问题的PHP脚本,因此我使用POST方法发送数据,问题在于此脚本一直告诉我“ Form is empty”,这意味着数据不是通过POST发送的(因为$ _POST为空)。当我尝试进行回应($ _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'];
}

我想了解为什么我的请求无法正常工作的原因,因为我认为自己没有语法或其他错误。 这是HTML文件中用于JQuery库的脚本。

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

我使用WAMPServer在本地运行我的站点,我已经进行了研究,但是问题可能是偶然的吗? 预先谢谢你

1 个答案:

答案 0 :(得分:0)

我再次通知您,我的数据最终通过$ _POST发送,如网络面板所示:

enter image description here

我还创建了一个var_dump($ _ SERVER),并且$ _SERVER ['HTTP_X_REQUESTED_WITH']的值为“ XML HTTPREQUEST”,这表明Ajax请求已启动。现在,我还有另一个问题:我没有客户端响应:目前,该程序似乎正在验证条件if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'),并且我有一个echo($encoded)的JSON格式,如下所示:

enter image description here

因此,我应该有一个客户端响应,实际上并非如此。

非常感谢您的回复,对于我的英语不好,我们深表歉意。

相关问题