This post demonstrates how to upload files to the server through AJAX. For the javascript part JQuery has been used.
Besides the file upload thing there are few other useful codes here:
- A generalised mail function. The function is capable of sending mails with attachments also.
- Ajax call using JQuery.
- Some server side validation codes.
Things might look a little jumbled up here, suggested to copy and paste the code to some IDE or editor first.
Form HTML
<span id="statusMessage"></span> <form action="" method="post" name="" id="form1" enctype="multipart/form-data" onsubmit="return sendCareerData()"> <input type="text" id="formName" name="formName" placeholder="Name" /> <input type="text" id="formEmail" name="formEmail" placeholder="Email" /> <input type="text" id="formPhone" name="formPhone" placeholder="Phone No." /> <input type="file" id="formFile" name="formFile" placeholder="Upload File" /> <input type="submit" id="button4" name="formSubmit" value="Submit" /> </form>
The Javascript part
<script type="text/javascript"> function sendCareerData() { var data = new FormData(document.getElementById("form1")); // make the AJAX request jQuery.ajax({ type: "POST", url: 'form-backend.php', data: data, mimeType:"multipart/form-data", contentType: false, cache: false, processData:false, dataType: 'json', success: function (data) { if (data.success == 0) //error on server side { /* error messages from server side validation */ var errors = '<ul>'; if (data.name_msg != '') errors += '<li>' + data.name_msg + '</li>'; if (data.email_msg != '') errors += '<li>' + data.email_msg + '</li>'; if (data.phone_msg != '') errors += '<li>' + data.phone_msg + '</li>'; jQuery("#statusMessage").html(errors); jQuery("#statusMessage").css("display","block"); } else if (data.success == 1) { jQuery("#statusMessage").html("Thank you! We will get in touch."); jQuery("#statusMessage").css("display","block"); } }, error: function (error) { jQuery("#statusMessage").html(error); jQuery("#statusMessage").css("display","block"); } }); return false; } </script>
The backend part using PHP
/******* form-backend.php *********/ <?php ob_start(); //to suppress any newlines being sent before the header call /********* a general mail sending function with or without attachment ***********/ function _mail($to, $from='', $subject = " ", $body = " ", $attachment = "" , $fileatt_type = "", $fileatt_name = "") { $headers = "MIME-Version: 1.0" . "\r\n"; if(strlen($from)) $headers .= 'From: ' . $from . "\r\n"; $headers .= 'Bcc: [email protected]' . "\r\n"; if(strlen($attachment)) //if attachment is there { $fp = fopen($attachment, "rb"); if(! $fp) { echo "Cannot attach file"; return false; } $buffer = fread($fp, filesize($attachment)); $attach_this=chunk_split(base64_encode($buffer)); fclose($fp); $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; /*'From: ' . $from . "\r\n" . 'Reply-To: ' . $from . "\r\n" .*/ $headers .= 'Content-Type: multipart/mixed; ' . " boundary="PHP-mixed-{$mime_boundary}"". "\r\n" . /* THIS BOUNDARY LINE AFTER CONTENT TYPE IS IMPORTANT */ //$headers .= 'X-Mailer: PHP/' . phpversion() ; -- causing problems $msg = "--PHP-mixed-{$mime_boundary}\r\n" . "Content-Type: text/html; charset="iso-8859-1"\r\n" . "Content-Transfer-Encoding: 7bit\r\n\r\n". $body . "\r\n"; $msg = "--PHP-mixed-{$mime_boundary}\r\n"; $msg .= "--PHP-mixed-{$mime_boundary}\r\n" . "Content-Type: {$fileatt_type}; " . " name="{$fileatt_name}"\r\n" . "Content-Disposition: attachment; " . " filename="{$fileatt_name}"\r\n" . "Content-Transfer-Encoding: base64\r\n\r\n" . $attach_this . "\r\n" . /* DON'T PUT TWO NEWLINES AFTER THE ATTACHMENT */ "--PHP-mixed-{$mime_boundary}--\r\n"; $body = $msg; } else //no attachment - send simple html mail { $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n"; $headers .= 'X-Mailer: PHP/' . phpversion(); } $mail_sent = mail($to, $subject, $body, $headers); $status = $mail_sent ? "1" : "0"; //1 - no error / success . 0 - error / failed return $status; } /**** a function for validating the user inputs **********/ function validate($name,$email,$phone) { $return_array = array(); $return_array['success'] = '1'; $return_array['name_msg'] = ''; $return_array['email_msg'] = ''; $return_array['phone_msg'] = ''; if($email == '') { $return_array['success'] = '0'; $return_array['email_msg'] = 'email is required'; } else { $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if(!preg_match($email_exp,$email)) { $return_array['success'] = '0'; $return_array['email_msg'] = 'enter valid email.'; } } if($name == '') { $return_array['success'] = '0'; $return_array['name_msg'] = 'Name is required'; } else { $string_exp = "/^[A-Za-z .'-]+$/"; if (!preg_match($string_exp, $name)) { $return_array['success'] = '0'; $return_array['name_msg'] = 'enter valid Name.'; } } if($phone == '') { $return_array['success'] = '0'; $return_array['phone_msg'] = 'Phone is required'; } else { $string_exp = "/^[0-9 -]+$/"; if (!preg_match($string_exp, $phone)) { $return_array['success'] = '0'; $return_array['name_msg'] = 'enter valid Phone.'; } } return $return_array; } /****** assigning the values to some variables for easy handling ********/ $name = $_POST['formName']; $email = $_POST['formEmail']; $phone = $_POST['formPhone']; $subject = $_POST['formSubject']; $file = $_FILES['formFile']['tmp_name']; $type = $_FILES['formFile']['type']; $return_array = validate($name,$email,$phone); // validate the user input and get the result in $return_array if($return_array['success'] == '1') //if input is okay then send the mail (with attachment) { $body = "<strong>Email = </strong>".$email."<br>"; $body .= "<strong>Name = </strong>".$name."<br>"; $body .= "<strong>Phone = </strong>".$phone."<br>"; if(strlen($_FILES['formFile']['tmp_name'])) //if attachment is there { _mail("[email protected]",$email,$subject,$body,$file,$type,$_FILES['formFile']['name']); } else { _mail("[email protected]",$email,$subject,$body); } } ob_end_clean();//discard any output thrown above header('Content-type: text/json'); echo json_encode($return_array); die(); ?>