Today let’s create an Ajax based contact form, that will allow users to send attachments in email message. This tutorial has been updated recently and is based on my recent post here. I’ve added Ajax part to the the example here, it will send form data without refreshing the page.
In order to send file as an attachment, first we must allow users to upload file using contact form. As you can see I have added file input field called file_attach to our form, you can add as many file input field with same name for multiple attachments.
jQuery Ajax Form Submit
Before we submit our form data to server using Ajax, we need to make sure input fields are not empty, and file type is allowable, and its size is not too big. For that we use HTML5 File API to read file data and validate it with our jQuery code. Once we validate our input fields, we can then send form data using jQuery $.ajax(). You can check-out my other post for more info about Ajax form submit.
Once the form data is sent to server successfully, the server should return JSON data, which we will grab and output message within the #contact_results div element.
Below is the complete PHP code that sends mail with attachments, taken from my other post PHP mail with Multiple Attachments. We will do simple server-side validation and play with PHP $_FILES before attaching file to mail header. If there’s no file uploaded for the attachment, we will simply switch to plain email.
That’s it, you can just download the sample file and start testing out the script, but I can’t show you the demo because it involves file uploading, you can try out the other demo here which works exactly same but without file uploading feature. Good luck!