0

I have a form and I want it to be send to my email. This is my HTML script with the form:

<form id="contact-form" class="contact-form style-2">
  <div class="form-row">
    <div class="form-col-2">
      <input type="text" name="cf-name" placeholder="Naam*">
    </div>
    <div class="form-col-2">

      <input type="text" name="cf-email" placeholder="Email*">

    </div>
  </div>

  <div class="form-row">
    <div class="form-col-2">

      <input type="tel" name="cf-phone" placeholder="Telefoonnummer">

    </div>
    <div class="form-row">
      <div class="form-col">

        <textarea name="cf-message" rows="2" placeholder="Vragen/verzoeken"></textarea>

      </div>
    </div>

    <button type="submit" class="btn style-3" data-type="submit">Verzend</button>
    <p class="text-size-small2">Velden met een * zijn vereist.</p>

</form>

I want to make use of AJAX and this is my script.

if ($('#contact-form').length) {

  var cf = $('#contact-form');
  cf.append('<div class="message-container"></div>');

  cf.on("submit", function (event) {

    var self = $(this),
      text;

    var request = $.ajax({
      url: "bat/mail.php",
      type: "post",
      data: self.serialize()
    });

    request.then(function (data) {
      if (data == "1") {

        text = "Your message has been sent successfully!";

        cf.find('input:not([type="submit"]),textarea').val('');

        $('.message-container').html('<div class="alert-box success"><i class="icon-smile"></i><p>' + text + '</p></div>')
          .delay(150)
          .slideDown(300)
          .delay(4000)
          .slideUp(300, function () {
            $(this).html("");
          });

      } else {
        if (cf.find('textarea').val().length < 10) {
          text = "Message must contain at least 10 characters!"
        }
        if (cf.find('input').val() == "") {
          text = "All required fields must be filled!";
        }
        $('.message-container').html('<div class="alert-box error"><i class="icon-warning"></i><p>' + text + '</p></div>')
          .delay(150)
          .slideDown(300)
          .delay(4000)
          .slideUp(300, function () {
            $(this).html("");
          });
      }
    }, function () {
      $('.message-container').html('<div class="alert-box error"><i class="icon-warning"></i><p>Connection to server failed!</p></div>')
        .delay(150)
        .slideDown(300)
        .delay(4000)
        .slideUp(300, function () {
          $(this).html("");
        });
    });

    event.preventDefault();

  });

}

And this is my PHP file:

<?php

    $user_email = "fr.sven.fr@hotmail.com";

    $mail = array(
        "name" => htmlspecialchars($_POST['cf-name']),
        "email" => htmlspecialchars($_POST['cf-email']),
        "subject" => htmlspecialchars($_POST['cf-subject']),
        "message" => htmlspecialchars($_POST['cf-message'])
    );

    function validate($arr){

        return !empty($arr['name']) && strlen($arr['message']) > 20 && filter_var($arr['email'],FILTER_VALIDATE_EMAIL);

    }

    if(validate($mail)){

        echo mail($user_email, $mail['subject'],
            "Name : {$mail['name']}\n"
            ."E-mail : {$mail['email']}\n"
            ."Message : {$mail['message']}"
        );

    }


?>

When I submit the file without typing filling in the form I get the correct error. When I fill in the message with less than 10 characters, I get the correct error, but when I fill in everything correctly I get the error:

Notice: Undefined index: cf-name in /Applications/MAMP/htdocs/Klus spanje/php/mail.php on line 7

Notice: Undefined index: cf-email in /Applications/MAMP/htdocs/Klus spanje/php/mail.php on line 8

Notice: Undefined index: cf-subject in /Applications/MAMP/htdocs/Klus spanje/php/bat/mail.php on line 9

Notice: Undefined index: cf-message in /Applications/MAMP/htdocs/Klus spanje/php/bat/mail.php on line 10 

I have no idea what I do wrong, can someone help?

Phil
  • 157,677
  • 23
  • 242
  • 245
FoxOnFireHD
  • 145
  • 11

1 Answers1

1

EDIT:

Ah, you added the php errors now, great!

So it is not seeing the right post variables. As you didn't provide the html of your form (which would be helpful next time!) I can only provide you a way to figure this out yourself :)

To figure out the right names that are posted, you can use

print_r($_POST);

in your php code. This will show you the key-value pairs that are sent from the client. Most likely the keys are just a bit different than you thought, but changing them to the ones printed by the above code should solve this error!

ORIGINAL: (because I am proud of making the screenshot ;))

My guess is, that the data returned by php is not exactly "1". You can confirm in the chrome console, under network the network tab:

Guide to get to networking tab request body

The green circle is just to find the requests made by javascript. You can also use console.log(data); but then what did I make this screenshot for? ;)

Now the problem with your code is that, when your javascript doesn't get "1", it will get to this code (with comments by me)

// These two conditions are both not met (as you fill in the form correctly)
if(cf.find('textarea').val().length < 10){
    // So text doesn't get set here
    text = "Message must contain at least 10 characters!"
}
if(cf.find('input').val() == ""){
    // Neither does this one
    text = "All required fields must be filled!";
}

// So at this point, the variable `text` has not gotten any value assigned,
// making it `undefined`. Which wouldn't be a problem,
// if it weren't for the fact you try to use it as is in the html here
$('.message-container').html('<div class="alert-box error"><i class="icon-warning"></i><p>'+text+'</p></div>')
    .delay(150)
    .slideDown(300)
    .delay(4000)
    .slideUp(300,function(){
        $(this).html("");
    });

Something you could do for now is, at least, provide a default error message:

    $('.message-container').html('<div class="alert-box error"><i class="icon-warning"></i><p>'+(text || 'Default error message')+'</p></div>')

But the thing is to either

  1. Make the php return the right value and run without an error, and if that is already working
  2. Make sure the javascript does match the correct data, without any spaces in the data. Maybe even using data.trim() (which removes whitespaces at the start and end of the string) could help here.

Hope this gives you a good point to start debugging the issue :)

Michiel Dral
  • 3,932
  • 1
  • 19
  • 21
  • 2
    I am not sure how this is a proper answer. This is your guess and overall debugging recommendations. Check the updated question – Dharman Jan 08 '19 at 23:56
  • @Dharman you are totally right, I didn't see the update yet :) – Michiel Dral Jan 08 '19 at 23:57
  • I think this answer can help OP as it clearly shows they should be looking in the browser console for AJAX requests and not opening the URL in their browser directly. – Phil Jan 09 '19 at 01:11