0

I need some help with my code. So i am trying to create a contact form with PHP and AJAX. It works because it send me the email when i try but i was trying to show a sentence either if it worked or if it didn't work. I guess i am a bit lost and i would enjoy some hints from you guys !

Here is 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");

})

}); `

Here is my 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); 
}   

And my View :

<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>

The array $ciao is there to tell me if yes or no it sent my email and then i want to get it in JSON so i can notify the user that the email was send or not. I get my email when i test it but i can't make the "notification" part works ! Thank you in advance for your help !

2 Answers2

0

Look, there is no data.ciao. There is just data and data contains either "nope" or "ok".

Both of these two solution would work:

  1. in contactController.php:
json_encode(['ciao' => $ciao]);
  1. or in contact.js
    if(data == 'ok'){
                 /* ... */   
        }

Just pick one of the solutions

0

Few things...

  1. Output the JSON using echo json_encode($value).

  2. If you are returning a JSON in your PHP and expecting a JSON in your JavaScript, then $value needs to be an array. $ciao (i.e. ok or nope) is not a JSON.

  3. Don't redirect within your AJAX script when an error occurs. It won't work.

  4. More of a personal opinion, sometimes it's better to return early rather than have nested IF statements.

Edit

After re-reading your post, it seems you want to remain on the same page and simply show the correct message depending on if the operation worked or not.

Simply, pass $ciao and $msg in your JSON. $ciao is used as a status flag to indicate if it worked or not and $msg is the message to show. On the client-side, when you get back the JSON response, you would check the JSON and make the appropriate HTML/CSS changes -- without having the need to do a reload of the page.

If that is not the case, simply check my original answer.

Example

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);
                }
            }
        }); 
    })
});
Mikey
  • 6,728
  • 4
  • 22
  • 45