Click here to Skip to main content
15,896,727 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to send a file alongwith other form data. Can any one suggest how to send file with data. Upload to be processed in PHP.

My code for index.html is below:
HTML
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function submitForm(){
inputs = document.forms["regForm"].elements;
			var data = "";
	    for (var i = 0; i < inputs.length; i++) {
			var name=inputs[i].name;
			var value=inputs[i].value;
			var type=inputs[i].type;
			if(type != "file"){
				if(i == 0 ){
					data = name+"="+value;	
				}
				else{
					data = data+"&"+name+"="+value;
				}
			}
	    }
	var action="process.php";
	var url = action+"?"+data;

	var fileInput = document.forms["regForm"].elements["pic"];
	var file=fileInput.files[0];
			
	var xmlhttp;
	if(window.XMLHttpRequest)
	{
		xmlhttp = new XMLHttpRequest();
		}
		else
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHttp");
		}

		xmlhttp.>
</head>

<body>
<form name="regForm" id="reg-form" method="post" action="process.php" enctype="multipart/form-data">
	User Name	:	<input type="text" name="uname" id="uname" value="" />
    User Pic	:	<input type="file" name="pic" id="pic" value="" />
	    <input type="button" name="submit" id="submit" value="Register" onclick="javascript:submitForm();">
</form>
<div id="err"></div>
</body>
</html>

And in process.php am simply displaying the input and file attributes which will be returned as response text and displayed in div id "err". Once I receive no error and display all attribute queried in process.php I can continue with any further processing.

Code for process.php:
PHP
	if(isset($_REQUEST['submit']) && $_REQUEST['submit'] == "Register"){
	echo	$uname=$_REQUEST['uname'];
	echo	$pic=$_FILES['pic']['name'];
	echo	$pic=$_FILES['pic']['type'];
	echo	$pic=$_FILES['pic']['size'];
	echo	$pic=$_FILES['pic']['tmp_name'];
	}
?>
Posted
Updated 28-Nov-14 23:40pm
v2

1 solution

Check this out:
1. Using FormData Objects[^]
 
Share this answer
 
v3
Comments
Member 11272892 29-Nov-14 6:14am    
Thanks Peter but am looking for pure Javascript Ajax solution not JQuery Ajax.
Regards,
Shubhajeet Saha
Peter Leow 29-Nov-14 6:19am    
That is the #1 option. Read the examples.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900