0% found this document useful (0 votes)
74 views

Simple Ajax Form With Email Attachment Using PHP1

The document describes a form that collects user information like name, email, and file attachment to send an email. It contains the HTML form, JavaScript to submit the form data via AJAX, and a PHP file to process the form submission. The PHP file validates the input, constructs the email message, attaches any files, and sends the email using mail function. It returns a JSON response depending on success or error.

Uploaded by

Brijesh Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Simple Ajax Form With Email Attachment Using PHP1

The document describes a form that collects user information like name, email, and file attachment to send an email. It contains the HTML form, JavaScript to submit the form data via AJAX, and a PHP file to process the form submission. The PHP file validates the input, constructs the email message, attaches any files, and sends the email using mail function. It returns a JSON response depending on success or error.

Uploaded by

Brijesh Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Filename: index.

html

This is the page where we have a simple form that collects all the information from the user to send an email via PHP
mail.

HTML Form
XHTML

1 <form id="contact-form" method="post" enctype="multipart/form-data">


2   <div class="form-group">
3     <label for="fname">First Name:</label>
4     <input type="text" class="form-control" id="fname">
5   </div>
6   <div class="form-group">
7     <label for="email">Email Address:</label>
8     <input type="email" class="form-control" id="email_address">
9   </div>
10   <div class="form-group">
11   <label for="attachment">File attachment:</label>
12    <input type="file" name="file_attach" class="input-field"/>
13   </div>
14
15   <button type="button" id="submit" class="btn btn-default btn-dark">Submit</button>
16 </form>
Above form have fields like First Name, Email Address and File attachment. Each input filed has its unique ID to
fetch the data once the form has submitted.

Note : We have set  enctype=”multipart/form-data” . This is used for file attachment.

The script that gather all information submitted by the Form and pass the data to process.php to send an email.

JavaScript

1 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
2 <script type="text/javascript">
3   $(document).ready(function() {
4           
5            $("#submit").click(function(e) {
6               
7                var proceed = true;
8  
9                if(proceed) //everything looks good! proceed...
10         {
11  
12            //data to be sent to server        
13             var m_data = new FormData();  
14             m_data.append( 'first_name', $('#fname').val());
15             m_data.append( 'email_address', $('#email_address').val());
16             m_data.append( 'file_attach', $('input[name=file_attach]')[0].files[0]);
17               
18             //instead of $.post() we are using $.ajax()
19             //that's because $.ajax() has more options and flexibly.
20  
21             $.ajax({
22               url: 'process.php',
23               data: m_data,
24               processData: false,
25               contentType: false,
26               type: 'POST',
27               dataType:'json',
28               success: function(response){
29                  //load json data from server and output message    
30                 if(response.type == 'error'){ //load json data from server and output message    
31                     output = '<div class="error">'+response.text+'</div>';
32                 }else{
33                     output = '<div class="success">'+response.text+'</div>';
34                 }
35                 $("#response").hide().html(output).slideDown();
36               }
37             });
38             
39
40         }
41  
42            });
43   });
44  
45 </script>
process.php

 Collect data send by jQuery using Ajax


 Construct the email
 Check whether have attachment or not
 Send Email using the PHP mail function.
PHP

1 <?php
2  
3  
4         
5     //Recepient Email Address
6     $to_email       = "[email protected]";
7  
8     //check if its an ajax request, exit if not
9     if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
10         $output = json_encode(array( //create JSON data
11             'type'=>'error',
12             'text' => 'Sorry Request must be Ajax POST'
13         ));
14         die($output); //exit script outputting json data
15     }
16  
17     //Sanitize input data using PHP filter_var().
18     $first_name      = filter_var($_POST["first_name"], FILTER_SANITIZE_STRING);
19     $email_address   = filter_var($_POST["email_address"], FILTER_SANITIZE_EMAIL);
20     $subject         = "Your Email Subject Goes Here...";
21   
22      
23     //Textbox Validation
24     if(strlen($first_name)<4){ // If length is less than 4 it will output JSON error.
25         $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
26         die($output);
27     }
28     
29  
30  
31     $message = '<html><body>';
32     $message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
33     $message .= "<tr style='background: #eee;'><td><strong>First Name:</strong> </td><td>" . strip_tags($_POST['first_name']) . "</td></tr>";
34     $message .= "<tr><td><strong>Email Address :</strong> </td><td>" . strip_tags($_POST['email_address']) . "</td></tr>";
35     $message .= "</table>";
36     $message .= "</body></html>";
37  
38  
39     $file_attached = false;
40     if(isset($_FILES['file_attach'])) //check uploaded file
41     {
42         //get file details we need
43         $file_tmp_name    = $_FILES['file_attach']['tmp_name'];
44         $file_name        = $_FILES['file_attach']['name'];
45         $file_size        = $_FILES['file_attach']['size'];
46         $file_type        = $_FILES['file_attach']['type'];
47         $file_error       = $_FILES['file_attach']['error'];
48  
49  
50  
51         //exit script and output error if we encounter any
52         if($file_error>0)
53         {
54             $mymsg = array(
55             1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
56             2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
57             3=>"The uploaded file was only partially uploaded",
58             4=>"No file was uploaded",
59             6=>"Missing a temporary folder" );
60              
61             $output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));
62             die($output);
63         }
64          
65         //read from the uploaded file & base64_encode content for the mail
66         $handle = fopen($file_tmp_name, "r");
67         $content = fread($handle, $file_size);
68         fclose($handle);
69         $encoded_content = chunk_split(base64_encode($content));
70         //now we know we have the file for attachment, set $file_attached to true
71         $file_attached = true;
72  
73  
74  
75         
76     }
77  
78  
79      
80     if($file_attached) //continue if we have the file
81     {
82        
83     // a random hash will be necessary to send mixed content
84     $separator = md5(time());
85  
86     // carriage return type (RFC)
87     $eol = "\r\n";
88  
89     // main header (multipart mandatory)
90     $headers = "From:Fromname <[email protected]>" . $eol;
91     $headers .= "MIME-Version: 1.0" . $eol;
92     $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
93     $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
94     $headers .= "This is a MIME encoded message." . $eol;
95  
96     // message
97     $body .= "--" . $separator . $eol;
98     $body .= "Content-type:text/html; charset=utf-8\n";
99     $body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
100     $body .= $message . $eol;
101  
102     // attachment
103     $body .= "--" . $separator . $eol;
104     $body  .= "Content-Type:".$file_type." ";
105     $body .= "Content-Type: application/octet-stream; name=\"" . $file_name . "\"" . $eol;
106     $body .= "Content-Transfer-Encoding: base64" . $eol;
107     $body .= "Content-Disposition: attachment; filename=\"".$file_name."\"". $eol;
108     $body .= $encoded_content . $eol;
109     $body .= "--" . $separator . "--";
110         
111     }
112     else
113     {
114         
115         $eol = "\r\n";
116         
117         $headers = "From: Fromname <[email protected]>" . $eol;
118         $headers .= "Reply-To: ". strip_tags($email_address) . "\r\n";
119         $headers .= "MIME-Version: 1.0\r\n";
120         $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
121         $body .= $message . $eol;
122  
123     }
124  
125  
126     $send_mail = mail($to_email, $subject, $body, $headers);
127  
128     if(!$send_mail)
129     {
130         //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
131         $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
132         die($output);
133     }else{
134         $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$first_name .' Thank you for your order, will get back to you shortly'));
135         die($output);
136     }
137  
138 ?>

You might also like