Alex Resiga
Alex Resiga

Reputation: 71

Prevent contact form from disappearing after submitting

I have the following PHP code:

<?php
$subjectPrefix = '[Contact via Site]';
$emailTo = '[email protected]';

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name    = stripslashes(trim($_POST['form-name']));
    $email   = stripslashes(trim($_POST['form-email']));
    $phone   = stripslashes(trim($_POST['form-tel']));
    $subject = stripslashes(trim($_POST['form-assunto']));
    $message = stripslashes(trim($_POST['form-mensagem']));
    $pattern = '/[\r\n]|Content-Type:|Bcc:|Cc:/i';

    if (preg_match($pattern, $name) || preg_match($pattern, $email) || preg_match($pattern, $subject)) {
        die("Header injection detected");
    }

    $emailIsValid = filter_var($email, FILTER_VALIDATE_EMAIL);

    if($name && $email && $emailIsValid && $subject && $message){
        $subject = "$subjectPrefix $subject";
        $body = "Nume: $name <br /> Email: $email <br /> Telefon: $phone <br /> Mesaj: $message";

        $headers .= sprintf( 'Return-Path: %s%s', $email, PHP_EOL );
        $headers .= sprintf( 'From: %s%s', $email, PHP_EOL );
        $headers .= sprintf( 'Reply-To: %s%s', $email, PHP_EOL );
        $headers .= sprintf( 'Message-ID: <%s@%s>%s', md5( uniqid( rand( ), true ) ), $_SERVER[ 'HTTP_HOST' ], PHP_EOL );
        $headers .= sprintf( 'X-Priority: %d%s', 3, PHP_EOL );
        $headers .= sprintf( 'X-Mailer: PHP/%s%s', phpversion( ), PHP_EOL );
        $headers .= sprintf( 'Disposition-Notification-To: %s%s', $email, PHP_EOL );
        $headers .= sprintf( 'MIME-Version: 1.0%s', PHP_EOL );
        $headers .= sprintf( 'Content-Transfer-Encoding: 8bit%s', PHP_EOL );
        $headers .= sprintf( 'Content-Type: text/html; charset="utf-8"%s', PHP_EOL );

        mail($emailTo, "=?utf-8?B?".base64_encode($subject)."?=", $body, $headers);
        $emailSent = true;
    } else {
        $hasError = true;
    }
} 
?> 

and the contact form:

      <?php if(!empty($emailSent)): ?>
    <div class="col-md-6 col-md-offset-3">
        <div class="alert alert-success text-center">Mesajul dumneavoastra a fost trimis cu succes!</div>
    </div>
<?php else: ?>
    <?php if(!empty($hasError)): ?>
    <div class="col-md-5 col-md-offset-4">
        <div class="alert alert-danger text-center">A apărut o eroare la trimiterea, vă rugăm să încercați din nou mai târziu.</div>
    </div>
    <?php endif; ?>

<div class="form" >
    <form action="<?php echo $_SERVER['REQUEST_URI']; ?>" id="contact-form" role="form" method="post">
        <div>
            <div >
                <input type="text"  id="form-name" name="form-name" placeholder="NUME" required>
            </div>
        </div>
        <div>

            <div>
                <input type="email"  id="form-email" name="form-email" placeholder="EMAIL" required>
            </div>
        </div>
        <div >

            <div>
                <input type="tel"  id="form-tel" name="form-tel" placeholder="TELEFON">
            </div>
        </div>
        <div>

            <div>
                <input type="text"  id="form-assunto" name="form-assunto" placeholder="SUBIECT" required>
            </div>
        </div>
        <div>

            <div >
                <textarea  id="form-mensagem" name="form-mensagem" placeholder="MESAJ" required></textarea>
            </div>
        </div>
        <div>
            <div>
                <button type="submit" class="button">Trimite</button>
            </div>
        </div>
    </form>
</div>
<?php endif; ?> 

and this contact-form.js for validation:

(function ($, window, document, undefined) {
    'use strict';

    function hasFormValidation () {
        return (typeof document.createElement('input').checkValidity === 'function');
    };

    function addError (el) {
        return el.parent().addClass('has-error');
    };

    if (!hasFormValidation()) {
        $('#contact-form').submit(function () {
            var hasError = false,
                name     = $('#form-name'),
                mail     = $('#form-email'),
                subject  = $('#form-assunto'),
                message = $('#form-mensagem'),
                testmail = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[@][A-z0-9_-]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
                $this    = $(this);

            $this.find('div').removeClass('has-error');

            if (name.val() === '') {
                hasError = true;
                addError(name);
            }

            if (!testmail.test(mail.val())) {
                hasError = true;
                addError(mail);
            }

            if (subject.val() === '') {
                hasError = true;
                addError(subject);
            }

            if (message.val() === '') {
                hasError = true;
                addError(message);
            }

            if (hasError === false) {
                return true;
            }

            return false;
        });
    }
}(jQuery, window, document)); 

After the user submits the contact form, it disappears, and i can't really understand why this happens and how could i get rid of this part. Can anyone point out the part which hides it after it was submited?

Upvotes: 0

Views: 799

Answers (3)

KFE
KFE

Reputation: 638

since you're already using contact-form.js, why not use AJAX to submit the form?

The form is disappearing because you're submitting the form to a new page and its redirecting. You would have a lot more control over the entire submission process using AJAX.

Upvotes: 1

RiggsFolly
RiggsFolly

Reputation: 94662

$_SERVER['REQUEST_URI'] in the action property will be the /?whatever is in the querystring probably nothing unless you ran this form from an anchor tag's href property.

And not a script/page name

This will put the script name into the action property of the page you ran to show the input page

<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" id="contact-form" role="form" method="post">

Alternatively, you can leave the action propery off the <form> tag completely and that will default to running this form again

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

Upvotes: 0

kerv
kerv

Reputation: 315

what you have to do is remove the form action that sends it to the server

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

Upvotes: 0

Related Questions