Ajax联系表:为什么它不起作用?

时间:2018-03-29 15:13:05

标签: php jquery ajax forms contact

我的代码需要一些帮助。所以我想尝试用PHP和AJAX创建一个联系表单。它的工作原理是因为它在我尝试时向我发送电子邮件,但我试图显示一个句子,如果它有效或者它不起作用。我想我有点失落,我会从你们那里得到一些暗示!

这是contact.js

$(submit).on("click", function(e){
    e.preventDefault();
    var formData = form.serialize();
    $.ajax({
        type : 'POST',
        url : form.attr('action'),
        data : formData,
        dataType : 'json',
        success: function(data){
            console.log('success');
            if(data.ciao == 'ok'){
                console.log('success');
                $('#nom').val('');
                $('#prenom').val('');
                $('#mail').val('');
                $('#message').val('');
                $(formMessage).removeClass('error');
                $(formMessage).addClass('success');
                $(formMessage).html('Mail envoyé avec succès'); 
            }


        },
        error: function(){
            if(data.ciao == "nope"){
                console.log('erreur');
            }
        }
    },"json");

})

}); `

这是我的contactController.php

public function envoiMailAction()
{
    if($this->data){
        $ciao = array();
        $spam = htmlentities($this->data['sujetMessage']);
        $nom = htmlentities($this->data['nom']);
        $prenom = htmlentities($this->data['prenom']);
        $mail = htmlentities($this->data['mail']);
        $message = htmlentities($this->data['message']);
        if(!empty($spam) && !($spam == '4' || strtolower($spam) == 'quatre'))
        {   
            $ciao = 'nope';
            Session::setFlash('Erreur SPAM' , 'danger');
            header('Location:index.php?controller=contact&action=afficherContact');
            exit();
        }
        else
        {
            $handler = new stringHandler();
            if($handler->checkInput($nom,NAME_MIN,NAME_MAX))
            {
                if($handler->checkInput($prenom,NAME_MIN,NAME_MAX))
                {
                    if(filter_var($mail, FILTER_VALIDATE_EMAIL))
                    {
                        if($handler->checkMessage($message)){
                            $ip           = $_SERVER["REMOTE_ADDR"];
                            $hostname     = gethostbyaddr($_SERVER["REMOTE_ADDR"]);
                            $destinataire = "amandine.dib@live.fr";
                            $objet        = "Message de " . $prenom." ".$nom;
                            $contenu      = "Nom de l'expéditeur : " . $nom . "\r\n";
                            $contenu     .= $message . "\r\n\n";
                            $contenu     .= "Adresse IP de l'expéditeur : " . $ip . "\r\n";
                            $contenu     .= "DLSAM : " . $hostname;

                            $headers  = "CC: " . $mail . " \r\n";
                            $headers .= "Content-Type: text/plain; charset=\"ISO-8859-1\"; DelSp=\"Yes\"; format=flowed /r/n";
                            $headers .= "Content-Disposition: inline \r\n";
                            $headers .= "Content-Transfer-Encoding: 7bit \r\n";
                            $headers .= "MIME-Version: 1.0";

                            $ciao = 'ok';
                            mail($destinataire, $objet, utf8_decode($contenu), 'From: amandine@exemple.com');
                            Session::setFlash('Message envoyé' , 'success');
                            header('Location:index.php?controller=contact&action=afficherContact');
                            exit();

                        }
                        else
                        {
                            $ciao = 'nope';
                            Session::setFlash('Erreur message' , 'danger');
                            header('Location:index.php?controller=contact&action=afficherContact');
                            exit();
                        }
                    }
                    else
                        {
                            $ciao = 'nope';
                            Session::setFlash('Erreur mail' , 'danger');
                            header('Location:index.php?controller=contact&action=afficherContact');
                            exit();
                        }
                }
                else
                        {
                            $ciao = 'nope';
                            Session::setFlash('Erreur prenom' , 'danger');
                            header('Location:index.php?controller=contact&action=afficherContact');
                            exit();
                        }
            }
            else
            {
                $ciao = 'nope';
                Session::setFlash('Erreur nom' , 'danger');
                header('Location:index.php?controller=contact&action=afficherContact');
                exit();
            }
        }   
    }
    else{
            $ciao = 'nope';
            Session::setFlash('Erreur envoi impossible' , 'danger');
            header('Location:index.php?controller=contact&action=afficherContact');
            exit();
    }
    header('Content-type: application/json');
    json_encode($ciao); 
}   

我的观点:

<div class="container" style="width: 50%;">
     <form action="index.php?controller=contact&action=envoiMail" id="formContact" method="post">
      <div class="form-row">
        <div class="form-group col-md-6">
          <label for="Nom">Nom</label>
          <input type="text" class="form-control" id="nom" name="nom" placeholder="Nom" required>
        </div>
        <div class="form-group col-md-6">
          <label for="Prenom">Prenom</label>
          <input type="text" class="form-control" id="prenom" name="prenom" placeholder="Prenom" required>
        </div>
      </div>
      <div class="form-group">
        <label for="inputEmail4">Email</label>
          <input type="email" class="form-control" id="mail" name="mail" placeholder="Email" required>
      </div>
      <div class="form-group sujetMessageBloc" style="display:none;">
        <label for="sujetMessage">Combien font 2+2 ?</label>
          <input type="text" class="form-control" id="sujetMessage" name="sujetMessage" placeholder="Combien font 2+2">
      </div>
      <div class="form-group">
        <label for="corpsMessage">Votre message</label>
        <textarea class="form-control" id="message" name="message" rows="3" required></textarea>
      </div>
      <div class="form-group">
      <input type="submit"  class="btn btn-primary" id="submitForm" name="submit" value="Envoyer" />
        </div>
    </form>
    <div id="formMessage"></div>
</div>

数组$ ciao是告诉我,如果是或否它发送了我的电子邮件然后我想用JSON得到它,所以我可以通知用户该电子邮件是否发送。当我测试它时,我收到了我的电子邮件,但我不能让“通知”部分工作!提前感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

看,没有data.ciao。只有data,数据包含"nope""ok"

这两种解决方案都可行:

  1. in contactController.php:
  2. json_encode(['ciao' => $ciao]);
    
    1. 或在contact.js
      &#13;
      &#13;
      if(data == 'ok'){
                   /* ... */   
          }
      &#13;
      &#13;
      &#13;
    2. 选择其中一个解决方案

答案 1 :(得分:0)

很少......

  1. 使用echo json_encode($value)输出JSON。

  2. 如果您在PHP中返回JSON并期望在JavaScript中使用JSON,那么$value需要是一个数组。 $ciao(即oknope)不是JSON。

  3. 发生错误时请勿redirect within your AJAX script。它不起作用。

  4. 更多的个人观点,有时候return early更好,而不是嵌套的IF语句。

  5. 修改

    重新阅读您的帖子后,您似乎希望保留在同一页面上,只需显示正确的消息,具体取决于操作是否有效。

    只需在您的JSON中传递$ciao$msg即可。 $ciao用作状态标志,以指示其是否有效,$msg是要显示的消息。在客户端,当您返回JSON响应时,您将检查JSON并进行适当的HTML / CSS更改 - 而无需重新加载页面。

    如果不是这样,只需查看我的original answer

    示例

    PHP

    public function envoiMailAction()
    {   
        // always expecting a JSON to come back
        header('Content-type: application/json');
    
        if (!$this->data) {
            echo json_encode(array( 'ciao' => 'nope', 'msg' => 'Erreur envoi impossible' )); 
            // if you are returning early in an AJAX script, you want to die or exit early
            exit;
        }
    
        $spam = htmlentities($this->data['sujetMessage']);
        $nom = htmlentities($this->data['nom']);
        $prenom = htmlentities($this->data['prenom']);
        $mail = htmlentities($this->data['mail']);
        $message = htmlentities($this->data['message']);
    
        if (!empty($spam) && !($spam == '4' || strtolower($spam) == 'quatre')) {   
            echo json_encode(array( 'ciao' => 'nope', 'msg' => 'Erreur SPAM' )); 
            exit;
        }
    
        $handler = new stringHandler();
    
        // note the !
        if (!$handler->checkInput($nom,NAME_MIN,NAME_MAX)) {
            echo json_encode(array( 'ciao' => 'nope', 'message' => 'Erreur nom' )); 
            exit;
        }
    
        if (!$handler->checkInput($prenom,NAME_MIN,NAME_MAX)) {
            echo json_encode(array( 'ciao' => 'nope', 'msg' => 'Erreur prenom' ));
            exit;
        }
    
        if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
            echo json_encode(array( 'ciao' => 'nope', 'msg' => 'Erreur mail' ));
            exit;
        }
    
        if (!$handler->checkMessage($message)){
            echo json_encode(array( 'ciao' => 'nope', 'msg' => 'Erreur message'));
            exit;
        }
    
        // if we made it here, then it passed the validations
        $ip           = $_SERVER["REMOTE_ADDR"];
        $hostname     = gethostbyaddr($_SERVER["REMOTE_ADDR"]);
        $destinataire = "amandine.dib@live.fr";
        $objet        = "Message de " . $prenom." ".$nom;
        $contenu      = "Nom de l'expéditeur : " . $nom . "\r\n";
        $contenu     .= $message . "\r\n\n";
        $contenu     .= "Adresse IP de l'expéditeur : " . $ip . "\r\n";
        $contenu     .= "DLSAM : " . $hostname;
    
        $headers  = "CC: " . $mail . " \r\n";
        $headers .= "Content-Type: text/plain; charset=\"ISO-8859-1\"; DelSp=\"Yes\"; format=flowed /r/n";
        $headers .= "Content-Disposition: inline \r\n";
        $headers .= "Content-Transfer-Encoding: 7bit \r\n";
        $headers .= "MIME-Version: 1.0";
    
        mail($destinataire, $objet, utf8_decode($contenu), 'From: amandine@exemple.com');
    
        echo json_encode(array( 'ciao' => 'ok', 'msg' => 'Message envoyé' ));
    }  
    

    JS

    $(function () {
        $(submit).on("click", function(e){
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: form.attr('action'),
                data: form.serialize(),
                dataType: 'json',
                success: function (data) {
                    // everything went well
                    if (data.ciao == 'ok'){
                        console.log('success');
                        $('#nom').val('');
                        $('#prenom').val('');
                        $('#mail').val('');
                        $('#message').val('');
                        $(formMessage).removeClass('error');
                        $(formMessage).addClass('success');
                        $(formMessage).html('Mail envoyé avec succès'); 
                    // something went bad and redirect to other page
                    } else {
                        $(formMessage).removeClass('success');
                        $(formMessage).addClass('error');
                        $(formMessage).html(data.msg);
                    }
                }
            }); 
        })
    });