Question

I cannot seem to find the problem in my code. I want the validation in php file to trigger the jquery notification plugin 'toastr', however, the php echo keeps publishing the php file message status to a new tab, instead. What am I doing wrong and how can I make the message appear in the notification, instead? The live version of my school site is here: Wright State University BMES Site and the problem can be replicated when submitting the Contact Us form. Thank you in advance :)

HTML:

<form action=send-contact.php method=post data-show-errors="true" class=contact-form id=contact-form-id data-parsley-validate>
<p class=half>
<input autofocus parsley-trigger="change" name=name required id=name placeholder="Type your name" class="testBox label_better" data-new-placeholder="Example: Sir Humphrey Charleston III" parsley-required="true">
</p>
<p class=half>
<input name=email id=email placeholder="Type your e-mail address" class="testBox label_better" data-new-placeholder="Example: humphrey.charleston@wright.edu" parsley-type="email" parsley-trigger="change" required parsley-required="true">
</p>
<p>
<select class="contactselect required" name=subject id=subject parsely-required="true" required parsley-trigger="change">
    <option value="" parsley-trigger="change">Please select one topic:</option>
    <option value="1" parsley-trigger="change">Information about BMES Chapter</option>
    <option value="2" parsley-trigger="change">Information about upcoming events</option>
    <option value="3" parsley-trigger="change">Other</option>
</select>
</p>
<p>
<textarea name=message id=message rows=12 cols=20 class="label_better_text" placeholder="Tell us what's on your mind." parsley-trigger="keyup" parsley-rangelength="[1,300]" required parsley-required="true"></textarea>
</p>
<p>
<button name=send type=submit onclick="$( '#contact-form-id' ).parsley('validate')" id=submit value=1>Send message</button>
<span class="color-red"><button onclick="$( '#contact-form-id' ).parsley( 'destroy' ); $('#contact-form-id').parsley();" name=reset type=reset value=1>Reset</button></span>
</p>
</form>
<script type=text/javascript>
jQuery(document).ready(function(c){
$('#contact-form').parsley();
$('#contact-form-id').submit(function(e) { 
    e.preventDefault();
    if ( $(this).parsley('validate') ) {
        $.post("send-contact.php", $(this).serialize()); 
        toastr.success('Thank you, we will attend to your message shortly.');
        $( '#contact-form-id' ).parsley( 'destroy' );
    } 
}); });
</script>

PHP:

<?php
$name = '';  
$subject = '';  
$email = '';
$message = '';
function getIp()
{if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip_address=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
if (!isset($ip_address)){
    if (isset($_SERVER['REMOTE_ADDR'])) 
    $ip_address=$_SERVER['REMOTE_ADDR'];
}
return $ip_address;
}
//taking the data from form 
$name = addslashes(trim($_POST['name']));   
$subject = addslashes(trim($_POST['subject'])); 
$email = addslashes(trim($_POST['email']));
$message = addslashes(trim($_POST['message']));
//form validation
$errors = array();
$fields = array();
if(!$name) {
$errors[] = "Please enter your name.";
$fields[] = "name";
}
$email_pattern = "/^[a-zA-Z0-9][a-zA-Z0-9\.-_]+\@([a-zA-Z0-9_-]+\.)+[a-zA-Z]+$/";
if(!$email) {
$errors[] = "Please enter your e-mail address.";
$fields[] = "email";
} else if(!preg_match($email_pattern, $email)) {
$errors[] = "The e-mail address you provided is invalid.";
$fields[] = "email";    
}
if(!$subject) {
$errors[] = "Please choose the subject of your message.";
$fields[] = "subject";
}
if(!$message) {
$errors[] = "Please enter your message.";
$fields[] = "message";
}
//preparing mail
if(!$errors) {
//taking info about date, IP and user agent
$timestamp = date("Y-m-d H:i:s");
$ip   = getIp();
$host = gethostbyaddr($ip); 
$user_agent = $_SERVER["HTTP_USER_AGENT"];
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\n";
$headers .= "From: $email\n";
$content = 'Subject: '.$subject.'<br>'.
'Name: '.$name.'<br>'.
'E-mail: '.$email.'<br>'.
'Message: '.$message.'<br>'.
'Time: '.$timestamp.'<br>'.
'IP: '.$host.'<br>'.
'User agent: '.$user_agent; 
//sending mail
$ok = mail("my-email-address-normally-goes-here","BMES Website Contact Us ", $content, $headers);
if($ok) {
    $response['msgStatus'] = "ok";
    $response['message'] = "Thank you for contacting us.  We will attend to your inquiry as soon as possible.";
} else {
    $response['msgStatus'] = "error";
    $response['message'] = "An error occured while trying to send your message. Please try again.";
}
} else {
$response['msgStatus'] = "error";
$response['errors'] = $errors;
$response['errorFields'] = $fields;
}
header('Content-type: application/json');
echo json_encode($response);
?>

Javascript:

$("form.contact-form").each(function(){
var form = $(this);
var button = form.find("button[type=submit]");
var buttonText = button.html();

button.click(function(e){
    e.preventDefault();

    var formTop = form.offset().top;
    var url = form.attr("action");
    var data = form.serialize();
    form.find("input, select, textarea, span").removeClass("error");
    form.find(".msg").remove();

    button.html("Sending...");

    $.post(url, data, function(response){
        var status = response.msgStatus;
        var msg = response.message;

        if(status == "ok") {
            form.prepend('<p class="msg success"><a class="hide" href="#">hide this</a>' + msg + '</p>');
            form.find("input, select, textarea").val("");
            var valField = form.find(".select .value");
            var selectField = valField.siblings("select");
            var selectedText = selectField.find("option").eq(0).html();
            valField.html(selectedText);

        } else if(status == "error") {
            if(response.errorFields.length) {
                var fields = response.errorFields;
                for (i = 0; i < fields.length; i++) {
                    form.find("#" + fields[i]).addClass("error");
                    form.find("select#" + fields[i]).parents(".select").addClass("error");
                }
                var errors = response.errors;
                var errorList = "<ul>";
                for (i = 0; i < errors.length; i++) {
                    errorList += "<li>" + errors[i] + "</li>";
                }
                errorList += "</ul>";
                form.prepend('<div class="msg error"><a class="hide" href="#">hide this</a><p>There were errors in your form:</p>' + errorList + '<p>Please make the necessary changes and re-submit your form</p></div>');

            } else form.prepend('<p class="msg error"><a class="hide" href="#">hide this</a>' + msg + '</p>');
        }
        $(".msg a.hide").click(function(e){
            e.preventDefault();
            $(this).parent().slideUp();
        });
        button.html(buttonText);
        window.scrollTo(0, formTop);
    }, 'json');
})
});
Was it helpful?

Solution 3

I have managed to solve the issue. Alterations are listed below for comparative purposes to not only help others but to also close this issue. A special thank you to @WhiteRuski for pointing me in the right direction. The PHP and HTML remain unchanged. Here is the new Javascript:

$("form.contact-form").each(function(){
var form = $(this);
var button = form.find("button[type=submit]");
var buttonText = button.html();

button.click(function(e){
    e.preventDefault();

    var url = form.attr("action");
    var data = form.serialize();

    // button.html("Sending...");
    button.html('<i class="fa fa-cog fa-lg fa-spin"></i>' + ' Sending ... ');

    $.post(url, data, function(response){
        var status = response.msgStatus;
        var msg = response.message;

        if(status == "ok") {
            toastr.success('<p>' + msg + '</p>');
            var valField = form.find(".select .value");
            var selectField = valField.siblings("select");
            var selectedText = selectField.find("option").eq(0).html();
            valField.html(selectedText);
        } else if(status == "error") {
            if(response.errorFields.length) {
                var fields = response.errorFields;
                for (i = 0; i < fields.length; i++) {
                    form.find("#" + fields[i]).addClass("error");
                    form.find("select#" + fields[i]).parents(".select").addClass("error");
                }
                var errors = response.errors;
                var errorList = "<ul>";
                for (i = 0; i < errors.length; i++) {
                    errorList += "<li>" + errors[i] + "</li>";
                }
                errorList += "</ul>";
                // toastr.error('<p>There were errors in your form:</p>' + errorList + '<p>Please make the necessary changes and re-submit your form</p>');  This lists the specific errpr in the field
                toastr.error('<p>There were a few errors in your form. Please resubmit with corrections.</p>');

            } else toastr.error('<p>' + msg + '</p>');
        }
        button.html(buttonText);
    }, 'json');
})
});

OTHER TIPS

Have you tried playing with your jquery a bit more? for instance, ajax instead of post.

something like this?

    button.click(function () {
        $.ajax({
            url: url,
            type: 'POST',
            data: form.serialize(),
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                if (data.msgSTatus == "ok"){
                    alert(data.message);
                    // play with html here once you know the page stays.
                 }
            },
            error: function (data) {
                alert('Fail.');
            }
        });
    });

As far as html appending goes, I would personally have an empty on the page already with an id, and just set the content of the div to the data that you receive, would make the js look much cleaner maybe..

Try including jquery before your other scripts. Also, use Firebug or build-in browser JS debugging tools to troubleshoot Javascript errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top