-1

I created contact form using phpmailer. and, it is working and send email fine. but, It does redirect in php file & then show message for successfully.

I want to show message on same contact form html page. and, I used below ajax jquery for that. but, mail does not send. and does get below message on same form html page.

There is a problem with the document!

How can i fixed this?

JS Code:

(function ($) {
    "use strict";

    var form = $('#contact-form'); // contact form
    var submit = $('#submit-btn'); // submit button
    
            // form submit event
            form.on('submit', function(e) {
                e.preventDefault(); // prevent default form submit
                $.ajax({
                    url: 'php/mail.php', // form action url
                    type: 'POST', // form submit method get/post
                    dataType: 'html', // request type html/json/xml
                    data: form.serialize(), // serialize form data
                    beforeSend: function() {
                        
                        submit.attr("disabled", "disabled");                    
                        var loadingText = '<span role="status" aria-hidden="true" class="spinner-border spinner-border-sm align-self-center mr-2"></span>Sending.....'; // change submit button text
                        if (submit.html() !== loadingText) {
                            submit.data('original-text', submit.html());
                            submit.html(loadingText);
                        }
                    },
                    success: function(data) {
                        //$('.alert-dismissible').remove();
                        submit.before(data).fadeIn(); // fade in response data 
                        form.trigger('reset'); // reset form
                        submit.html(submit.data('original-text'));// reset submit button text
                        submit.removeAttr("disabled", "disabled");
                    },
                    error: function(e) {
                        alert('error');
                    }
                });
            });
})(jQuery);

mail.php Code:

<?php

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    $myCompanyName = "CompanyName";
    $myCompanyEmail = "noreply@CompanyName.com";
    $myCompanyEmailPassword = "CompanyEmailPassword";
    
    $myPersonalEmail = "personalEmail@gmail.com";

    require './phpmailer/src/Exception.php';
    require './phpmailer/src/PHPMailer.php';
    require './phpmailer/src/SMTP.php';

    if(isset($_POST['submit'])) {

        $mail = new PHPMailer(true);

        //$mail->SMTPDebug = 0;

        $mail->Host = 'smtp.mboxhosting.com';
        $mail->SMTPAuth = true;
        $mail->Username = $myCompanyEmail;
        $mail->Password = $myCompanyEmailPassword;
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        $mail->setFrom($myCompanyEmail, $myCompanyName);
        $mail->addAddress($myPersonalEmail);
        $mail->addReplyTo($_POST['email'], $_POST['name']);

        $mail->isHTML(true);
        $mail->Subject = 'My Subject';
        $mail->Body = $_POST['message'];

        try {
            $mail->send();
            echo 'Your message was sent successfully!';
        } catch (Exception $e) {
            echo "Your message could not be sent! PHPMailer Error: {$mail->ErrorInfo}";
        }
        
    } else {
        echo "There is a problem with the document!";
    }
    
?>

Form HTML Code:

<form id="contact-form" action="php/mail.php" method="post">
              <div class="row">
                <div class="col-lg-6">
                  <div class="form-group">
                    <input name="name" type="text" class="form-control rounded-lg" required placeholder="Name">
                  </div>
                </div>
                <div class="col-lg-6">
                  <div class="form-group">
                    <input name="email" type="email" class="form-control rounded-lg" required placeholder="Email">
                  </div>
                </div>
              </div>
              <div class="form-group">
                <textarea name="message" class="form-control rounded-lg" rows="3" required placeholder="Tell us more about your needs........"></textarea>
              </div>
              <p class="text-center mt-5 mb-0">
                <button id="submit-btn" class="btn btn-outline-dark rounded-lg shadow-none d-inline-flex" name="submit" type="submit">Send Message</button>
              </p>
            </form>
HDP
  • 4,005
  • 2
  • 36
  • 58
  • What have you tried to check **why** the mail is not sent? How is that related to AJAX itself? – Nico Haase Jul 10 '20 at 06:05
  • Normally, It does send email and redirect mail.php page and does show message successfully. and also, does get mail in my inbox. but, if, I try with above mention my JS code. So, It does not send email. and it show message. `There is a problem with the document!` So, I can not understated. issue is in php or js. – HDP Jul 10 '20 at 06:13
  • if you get `There is a problem with the document!` then `$_POST['submit']` is not send to the php file. – Stender Jul 10 '20 at 06:13
  • insted of `data: form.serialize()` you could send the data as an json-array yourself by selecting the values of the forn, and then you can check for them insted in your php, and wouldn't have this problem anymore I guess. – Stender Jul 10 '20 at 06:16
  • like so : `data: { 'submittedName': nameToSubmitValue, 'submittedEmail': emailToSubmitValue }` – Stender Jul 10 '20 at 06:19
  • So, what have you tried to debug the problem? Why not start to use XDebug, or even `var_dump` to see which parts of your code work and which don't? – Nico Haase Jul 10 '20 at 07:23
  • @NicoHaase I am not expert of php. I am html developer. Here I am trying to create contact form with PHPmailer. Thanks. – HDP Jul 10 '20 at 07:39

2 Answers2

1

I had same issue, i resolve with hidden input in form with random name like:

<input type="hidden" name="test">

then in php file:

if(isset($_POST['test'])) {

And work, the issue coming because form.serialize() or new FormData() don't use submit button.
Another way is include button submit like here

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
  • Here, I am use jquery. if, I want to use action/method. So, how to it? if, I don't want to use hidden input. any possibility. – HDP Jul 10 '20 at 06:29
  • hidden input is only for use isset in php file, you sent it with ajax. else see my link in answer. – Simone Rossaini Jul 10 '20 at 06:37
  • Thanks. this is working fine with your suggestion. We have use `if(isset($_POST['name'])) {` So. will not need to add hidden input. – HDP Jul 10 '20 at 11:49
1

You have to remove the action="php/mail.php" method="post" because this is handled by jQuery and you have to add a hidden input like <input type="hidden" name="iamhidden" /> to the form and then replace the if(isset($_POST['submit'])) with if(isset($_POST['iamhidden']))

Steven2105
  • 540
  • 5
  • 20
  • Here, I am use jquery. if I want to use action/method. so, how to it? – HDP Jul 10 '20 at 06:32
  • You prevent the default submit event so it won't even get called. The Ajax method is sending the data to the php application. – Steven2105 Jul 10 '20 at 06:33
  • 1
    This is not a safe approach as it will break the form if Javascript is disabled. The right way to deal with this is to leave the action as usual, but attach an event listener using jQuery that disables the default action using `preventDefault` in your form action handler in jQuery. This way the form stays working if JS is disabled, but uses jQuery if it is enabled; This approach is called "progressive enhancement". – Synchro Jul 10 '20 at 06:43