• Blogs (9)
    • 📱 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • PHP and jQuery: send email

    Blogs20112011-07-02


    I wrote a very compact, simple web app: send email via a web page. The functions use PHP and jQuery(version 1.5.1), include:

    • form validation
      I use a excellent jQuery plugin: Validation Engine to do the form validation.
    • Ajax Style send email
      use jQuery’s $.ajax(), and ‘click’ event to send email instead of form submit.

    (1) the header part: to launch all the need js and css file.

    http://js/jquery-1.5.1.min.js
    http://js/jquery.validationEngine-en.js
    http://js/jquery.validationEngine.js
    <link rel="stylesheet" type="text/css" href="css/validationEngine.jquery.css" />

    (2) form and its javascript action:

    <form id="request_form" method="post" action="<?=$_SERVER['PHP_SELF'];?>">
      <p>Organization:</p>
      
        
      
      <p>Name:</p>
      
        
      
      <p>Email:</p>
      
        
      
      <p>Phone #:</p>
      
        
      
      <input id="request_submit" value="Send Request" type="submit">
    </form>
    
    $(document).ready(function() {
      $("#request_submit").click( function(event) {
    	$("#request_form").validationEngine();
    	event.preventDefault();
    	if ($("#request_form").validationEngine({returnIsValid:true})) {
    		alert( $("#request_form").serialize());
    		$.ajax({
    			type: $("#request_form").attr('method'),
    			url: $("#request_form").attr('action'),
    			data: $("#request_form").serialize(),
    			success: function(data) {
    				alert(data);
    				$("#request_form").append('Successfully send out this email request!');
    			}
    		});
    	}
      });
    });

    (3) PHP process:

    <?php
    
    if(isset($_POST['email'])) {
    	if ( !check_email( trim($_POST['email']) )) {
    		echo 'Please enter a valid email address<br />';
    	}
    	else send_email();
    }
    exit;
    function check_email($emailAddress) {
    	if (preg_match('/b[A-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z]{2,4}b/i', $emailAddress)){
    		$emailArray = explode("@",$emailAddress);
    		if (checkdnsrr($emailArray[1])){
    			return true;
    		}
    	}
    	return false;
    }
    function send_email() {
    	$message = "nOrganization: " . $_POST['organization'] .
    		"nName: " . $_POST['name'] .
    		"nEmail: " . $_POST['email'] .
    		"nPhone: " . $_POST['phone'];
    
    	$message .= "nnBrowser Info: " . $_SERVER["HTTP_USER_AGENT"] .
    		"nIP: " . $_SERVER["REMOTE_ADDR"] .
    		"nnDate: " . date("Y-m-d h:i:s");
    
    	$siteEmail = 'test@test.com';
    	$emailTitle = 'Request from examples.com';
    	$thankYouMessage = "Thank you for contacting us, we'll get back to you shortly.";
    
    	if(! mail($siteEmail, $emailTitle, $message, 'From: ' . $_POST['name'] . ' <' . $_POST['email'] . '>'))
    		echo 'Mail can not sent.';
    }
    ?>

    It works pretty cool.