2

I'm using this code from codepen for my contact form.

The issue that I'm experiencing is that once you click the "send" button, you leave the page where the contact form is to arrive to sendmessage.php.

What I'd like to see is the normal behavior of a form: when you click "send" (and the message is transmitted successfully), you stay on the same page, the "send" button disappears and is replaced by the "success" message without leaving or reloading the page where the form is placed..

Any idea what the issue is with the current code? You can test my live example here

Many thanks,

HTML:

<form class="well form-horizontal" action="../sendmessage.php" method="post"  id="contact_form">

Javascript:

  $(document).ready(function() {
    $('#contact_form').bootstrapValidator({
        // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            first_name: {
                validators: {
                        stringLength: {
                        min: 2,
                    },
                        notEmpty: {
                        message: 'Please supply your first name'
                    }
                }
            },
            email: {
                validators: {
                    notEmpty: {
                        message: 'Please supply your email address'
                    },
                    emailAddress: {
                        message: 'Please supply a valid email address'
                    }
                }
            },            
            message: {
                validators: {
                      stringLength: {
                        min: 10,
                        max: 200,
                        message:'Please enter at least 10 characters and no more than 200'
                    },
                    notEmpty: {
                        message: 'Please supply a description of your project'
                    }
                    }
                }
            }
        })
        .on('success.form.bv', function(e) {
            $('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...

                $('#contact_form').data('bootstrapValidator').resetForm();

            // Prevent form submission
            e.preventDefault();

            // Get the form instance
            var $form = $(e.target);

            // Get the BootstrapValidator instance
            var bv = $form.data('bootstrapValidator');

            // Use Ajax to submit form data
            $.post($form.attr('action'), $form.serialize(), function(result) {
                console.log(result);
            }, 'json');
        });
});

Content of sendmessage.php:

<?php

require 'PHPMailer/PHPMailerAutoload.php';

$mail = new PHPMailer;
$mail->CharSet = 'utf-8';

//Enable SMTP debugging. 
$mail->SMTPDebug = false;                               
//Set PHPMailer to use SMTP.
$mail->isSMTP();            
//Set SMTP host name                          
$mail->Host = "smtp.elasticemail.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;                          
//Provide username and password     
$mail->Username = "xyz";                 
$mail->Password = "xyz";                           
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";                           
//Set TCP port to connect to 
$mail->Port = 2525;                                   

$mail->From = $_POST['email'];
$mail->FromName = $_POST['first_name'];

$mail->addAddress("xyz@gmail.com");
//CC and BCC
$mail->addCC("xyz@outlook.com");
$mail->addBCC("");

$mail->isHTML(true);

$mail->Subject = "New message from " . $_POST['first_name'] . $_POST['last_name'];
$mail->Body =  $_POST['message']."<br><br>From page: ". str_replace("http://", "", $_SERVER['HTTP_REFERER']) . "<br>" . $_SERVER ['HTTP_USER_AGENT'] ;

$response = array();
if(!$mail->send()) {
  $response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
} else {
  $response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}

/* send content type header */
header('Content-Type: application/json');

/* send response as json */
echo json_encode($response);

?>
Greg
  • 3,025
  • 13
  • 58
  • 106
  • why is header('Location: page.php'); not a god choice ? – SnakeFoot Mar 28 '16 at 13:04
  • you could add the onclick="return confirm('Are you sure you want to send?')" function – SnakeFoot Mar 28 '16 at 13:06
  • Hi, thanks for the suggestions, but that would not be ideal for me, the contact form is at the bottom of each page of my website, and I don't want the users to leave the page they are visiting, I just want a success message to appear when the click on "send" and the message is sent successfully. – Greg Mar 28 '16 at 13:08
  • mabye this is for you : http://stackoverflow.com/questions/2269307/using-jquery-ajax-to-call-a-php-function – SnakeFoot Mar 28 '16 at 13:10
  • or this :http://stackoverflow.com/questions/27716499/how-to-call-a-php-script-function-on-a-html-button-click – SnakeFoot Mar 28 '16 at 13:13
  • why can't you use $.ajax and check the success callback method to verify whether the email call is made or not. I don't see any problem with php file. – Ganesh Babu Mar 28 '16 at 13:22
  • Thanks Ganesh. I guess I could but the issue is that I don't know what to adapt in the existing code in order to to this (I have no JS/PHP knowledge). Could you help me? – Greg Mar 28 '16 at 13:26
  • @Greg I hope your code is correct regarding bootstrap validator. when I tried with your code the only issue I got is with the reset line. can you replace $('#contact_form').data('bootstrapValidator').resetForm() with $("form#contact_form")[0].reset() and check. also, your form cannot redirect to another page since the following line is there in your code." e.preventDefault()". so don't remove action="sendmessage.php" from your html code – Ganesh Babu Mar 28 '16 at 13:37
  • Thanks. Yes the code is correct, it comes from http://codepen.io/jaycbrf/pen/iBszr – Greg Mar 28 '16 at 13:43
  • @Greg I couldn't get your previous comment. Is that issue fixed? If fixed, post the issue with answer in the answer section, so that some will benefit in future. – Ganesh Babu Mar 28 '16 at 13:47
  • Hi Ganesh, there is no issue with the code, the validation works, etc. What I'm trying to figure out is how to call the php mail script without leaving the page where the form is placed. – Greg Mar 28 '16 at 13:53
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/107555/discussion-between-ganesh-babu-t-y-and-greg). – Ganesh Babu Mar 28 '16 at 13:57

2 Answers2

1

Have you tried doing just returning false on the submit event?

$('#contact_form').on('submit', function(event) {
  event.preventDefault();
  return false;
});
gmaliar
  • 5,294
  • 1
  • 28
  • 36
  • Thanks. I can try. Where should I put this in my existing code? – Greg Mar 28 '16 at 14:26
  • You can attach it right above the `.on('success.form.bv', function(e) {' as another `.on` event handler. – gmaliar Mar 28 '16 at 14:29
  • Thanks, I have tried to copy/paste it just above the .on('success.form.bv', function(e) but it breaks the code, must be a syntax error?. What is the purpose of this code? Would it prevent users to leave the page when they click the "send" button ? Many thanks – Greg Mar 28 '16 at 14:33
  • Yes you would have to take off the last semi-colon. `;` to be able to chain the `on` functions and yes it would prevent the page from changing. – gmaliar Mar 28 '16 at 14:44
  • Thanks. So now, I don't leave the page anymore when I click "send", but the form does not get sent. Perhaps again a syntax issue? (I have copy/pasted the original code + your addition in a jsfiddle to ease the review) https://jsfiddle.net/nwk9dLrn/ – Greg Mar 28 '16 at 14:55
  • @Greg, eventually to get it working I moved your code to the submit handler and it works out. https://jsfiddle.net/nwk9dLrn/1/ – gmaliar Mar 29 '16 at 07:55
0

You need to update your bootstrapvalidator.min.js file 0.4.5 to latest file

https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.min.js

I have created a fiddle https://jsfiddle.net/nwk9dLrn/8/ plz check but i have not added its ajax.php file but you can see it in console. when you update your bootstrapvalidator file this will work.

$('#contact_form').bootstrapValidator({
        // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            first_name: {
                validators: {
                        stringLength: {
                        min: 2,
                    },
                        notEmpty: {
                        message: 'Please supply your first name'
                    }
                }
            },
            email: {
                validators: {
                    notEmpty: {
                        message: 'Please supply your email address'
                    },
                    emailAddress: {
                        message: 'Please supply a valid email address'
                    }
                }
            },            
            message: {
                validators: {
                      stringLength: {
                        min: 10,
                        max: 200,
                        message:'Please enter at least 10 characters and no more than 200'
                    },
                    notEmpty: {
                        message: 'Please supply a description of your project'
                    }
                    }
                }
            }
        })
        .on('success.form.bv', function(e) {
            // Prevent form submission
            e.preventDefault();

            // Get the form instance
            var $form = $(e.target);

            // Get the BootstrapValidator instance
            var bv = $form.data('bootstrapValidator');

            // Use Ajax to submit form data
            $.post($form.attr('action'), $form.serialize(), function(result) {                
                $("#success_message").show();

                $('#contact_form input').val('');
            }, 'json');
        });
Akshay Sharma
  • 1,042
  • 1
  • 8
  • 21
  • Thanks a lot! It does partially work now (I get the success message without leaving the page). What was the issue? The only remaining issue is that it shows the success message even when the message is actually not sent (I have tried to delete everything that was in sendmessage.php... and I'm still getting the success message). Does that mean that sendmessage.php does not "communicate" with the javascript to "give the green light" to display the success message? Thanks – Greg Mar 31 '16 at 06:58
  • You need to hide success message div with inline css and try this code $.post($form.attr('action'), $form.serialize(), function(result) { $("#success_message").show(); $('#contact_form input').val(''); }, 'json'); here when form successfully submitted then $("#success_message").show();// it will show the success div – Akshay Sharma Mar 31 '16 at 07:07