Send mailer using phpMailer jquery ajax

i am using bootstrap anh here is my HTML Body

Contact.php

`

	<link href='https://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
    <link href='custom.css' rel='stylesheet' type='text/css'>
		 <div class="container">

        <div class="row">

            <div class="col-lg-8 col-lg-offset-2">

                <h1>Contact us</h1>

              


                <form id="contact-form" method="post" action="" role="form">

                    <div class="messages"></div>

                    <div class="controls">

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="form_name">Firstname *</label>
                                    <input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
                                    <div class="help-block with-errors"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="form_lastname">Lastname *</label>
                                    <input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
                                    <div class="help-block with-errors"></div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="form_email">Email *</label>
                                    <input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
                                    <div class="help-block with-errors"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="form_phone">Phone</label>
                                    <input id="form_phone" type="tel" name="tel" class="form-control" placeholder="Please enter your phone">
                                    <div class="help-block with-errors"></div>
                                </div>
                            </div>
                             <div class="col-md-12">
                                <div class="form-group">
                                    <label for="form_phone">Subject</label>
                                    <input id="form_phone" type="tel" name="sub" class="form-control" placeholder="Please enter Subject*" required="required" data-error="Valid email is required.">
                                    <div class="help-block with-errors"></div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="form_message">Message *</label>
                                    <textarea id="form_message" name="mssg" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please,leave us a message."></textarea>
                                    <div class="help-block with-errors"></div>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <input type="submit" class="btn btn-success btn-send" value="Send message">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <p class="text-muted"><strong>*</strong> These fields are required.</p>
                            </div>
                        </div>
                    </div>

                </form>

            </div><!-- /.8 -->

        </div> <!-- /.row-->

    </div> <!-- /.container-->

    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="validator.js"></script>
    <script src="contact.js"></script>`

send.php

 `<?php
require '/home/megs8c16/public_html/phpMailer/PHPMailerAutoload.php';
header('Content-Type: application/json');
$fname = $_POST['name'];
$lname = $_POST['surname'];
$mail = $_POST['email'];
$subject = $_POST['sub'];
$message = $_POST['mssg'];
$tel = $_POST['tel'];

$mail = new PHPMailer;
$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'wc-122.atnoc.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'support@xxxxxx.com';                 // SMTP username
$mail->Password = 'xxxxxxxxxxxxx';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25;                                    // TCP port to connect to

$mail->setFrom($_POST['email'], $_POST['fname']);
// Add a recipient
$mail->addAddress('rseifi.a73@gmail.com');               // Name is optional


$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = $subject;
$mail->Body    = "$message Phone $tel";
$mail->AltBody = $message;
if(!$mail->send()) {
echo 'Message could not be sent.';
         echo 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
    echo 'Message has been sent';
    }
    ?>`

jquery ajax contect.js

  `$(function () {
        $('#contact-form').validator();

     $('#contact-form').on('submit', function (e) {
    if (!e.isDefaultPrevented()) {
        var url = "send.php";

        $.ajax({
            type: "POST",
            url: url,
            data: $(this).serialize(),
            success: function (data)
            {
                var messageAlert = 'alert-' + data.type;
                var messageText = data.message;

                var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                if (messageAlert && messageText) {
                    $('#contact-form').find('.messages').html(alertBox);
                    $('#contact-form')[0].reset();
                }
            }
        });
        return false;
    }
})
});`

so i see you did not experience any problems with that. thats why you shared the code with us?

Yes you areright

Is there any question you had about the posted code, or was there any discussion that you wanted to start? If not, I’m finding it difficult understanding why you posted this code to begin with.

Hi all, i dont know why you posted it also, but its very welcome to me. Past days i was busy with this. I’m using the exact same bootstrap form (you have it from bootstrapious right?). Anyhow i tried to use it but the form is not send, there is no action. Are you sure action="" should be empty?

Edit #1: Alright i have it to work, not yet perfectly but that later on. You also have to add

  • class.phpmailer.php
  • class.pop3.php
  • class.smtp.php
    (you can find it on github, just google for ‘PHPMailer’)

There are some things, i hope @Riyaz_saifi has an answer to that… :

  • send.php is directly visitable and gives “Message has been sent”, which will result into receiving empty e-mails.

  • When you hit send, you don’t get the bootstrap “send success message”
    This has to be changed i guess:

    echo ‘Message could not be sent.’;
    echo 'Mailer Error: ’ . $mail->ErrorInfo;
    } else {
    echo ‘Message has been sent’;
    }

In the original bootstrapform there is something like:

$responseArray = array('type' => 'succes', 'message => $okMessage);

I dont know how to combine this two, but if this is fixed i think its a very good form. If it works like a charm, i think it has to be put on github.

Hi @Jorus! I too don’t know why this has been posted, but I think I can answer some of your questions. :-)

You’d normally check if isset($_POST['name']) etc. for the required fields, and redirect to the form again if not. Client side form validation is never (!) enough; it’s certainly a nice UX bonus, but it can’t replace server side validation (or sanitization, for that matter).

Yes, you might write such a success page to which you’d redirect when the message has been sent, like

header('Location: http://my-success-page.html');

although that doesn’t make sense in AJAX context. There I prefer to use HTTP status codes so you can trigger the success/error callbacks.

1 Like

D’oh on me! :-D Yes, as you said then.

I solved it by doing this:

if(!$mail->send()) {
        $responseArray = array('type' => 'danger', 'message' => $errorMessage);
    } else {
        $responseArray = array('type' => 'success', 'message' => $okMessage);
        }
    }

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 {
    echo $responseArray['message'];
    }

}

I think i will post the whole script to github. This is a very nice form to share i guess, dont you think?

1 Like

Working thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.