Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Prevent the contact form submit bottom to redirect the page Reply To: Prevent the contact form submit bottom to redirect the page

#149705
__
Participant

~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
Regarding safety: always validate all user-submitted data.

(This is always relevant; it has nothing to do with whether or not you use ajax.)

You cannot trust user input. Sometimes it will have mistakes. Sometimes it will be an attack. In this particular case, you use the email field from the form in your From header. This opens your form to header injection (oversimplified example):

Name:    [ Mallory ]
Email:   [ mal@attack\r\nBCC: <everyone on my spam list> ]
Message: [ Free viagra! ]

bam! You’re a spam server.

Fixing this is simple: validate that the email field really does contain an email address.

<?php
#  ... snip ...  #
$email = filter_var( $_POST['email'],FILTER_VALIDATE_EMAIL );
if( ! $email ){
    /* not a valid email - insert error message here */ 

    /* and exit */
    die;
}
#  ... snip ...  #

~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
Regarding functionality:

You’re showing the notice no matter what: it will say “thank you” if the ajax request succeeds, even if sending the mail failed. Your die message (which is a really bad way of handling errors anyway) will never be seen.

I’d suggest changing your php script to return a value – true or false, for example, depending on whether the mail was sent:

<?php
#  ... snip ...  #

# $sent will be TRUE if mail() is successful; FALSE if not
$sent = mail( $recipient,$subject,$formcontent,$mailheader );

# format your response as JSON; print
print json_encode( array( 'sent'=>$sent ) );
# and exit
die;

Then check that value when you get the ajax response:

$.ajax({ 
    type : "POST"
   ,url : "mail.php"
   ,data : dataString
   ,dataType: "json" /*<-- you expect a JSON response from your script */
   ,cache : false
   ,success : function( responseData ) { 
        if( responseData.sent === true ){
            /* mail successfully sent */
            $( ".form" ).hide(); 
            $( "#success-notice" ).fadeIn( 400 ); 
        }
        else{
            /* mail not sent.
                you could add more information
                (error messages, for example)
                to the json response for use here. */
            $( "#failure-notice" ).fadeIn( 400 );
        }
    } 
});