Submit forms and upload pictures using FormData form data objects

Using FormData form data objects in H5, the name and value of all form elements in the form form form can be combined into a request string and submitted to the background.You can use js to simulate a series of form controls with some key-value pairs, or you can use the send() method of XMLHttpRequest to submit the form asynchronously.

<body>
	<div>
		<h2>Collect form data without refreshing</h2>
		<form>
			<p>User name : <input type="text" name="username" value="jnjk" /></p>
			<p>Password : <input type="password" name="password" value="123456" /></p>
			<p>Mailbox : <input type="text" name="email" value="jnjk@qq.com" /></p>
			<p>Head portrait : <input type="file" name="headimg" value="" /></p>
			<img src="" id="headimg" />
			<p style="text-align:center;"><input type="submit"  value="Submit" /></p>
		</form>
	</div>
</body>

There are regular text character submissions and file submissions in the form, and all form field data can be retrieved using the FormData object.

<script type="text/javascript">
	var fm = document.getElementsByTagName("form")[0];
	var himg = document.getElementById("headimg");
	fm.addEventListener("submit",function(e){
		//Collect form data using FormData form data objects
		//var fdata = new FormData(fm); //Collect form information for FM
		var fdata = new FormData(this);	//Collect form information for fm
		
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4 && xhr.status == 200){
				var msg = xhr.responseText;
				eval("var return_obj = "+msg);		//Convert returned json string to object
				console.log(return_obj);
				if(return_obj.status){
					himg.setAttribute('src',return_obj.data.headimg);
					himg.setAttribute('style','display:block');
				}else{
					alert(return_obj.data);
				}
			}
		}
		xhr.open('post','data.php');
		xhr.send(fdata);
		
		e.preventDefault();	//Prevent Browser Default Actions
	});
</script>

data.php

<?php

$data = $_POST;					//Common Form Fields
$file = $_FILES['headimg'];		//File Upload

if($file['error'] > 0) exit(json_encode(array('status'=>0,'data'=>'File Exception')));

$save_path = './upload/'.date('Ymd').'/';
if(!is_dir($save_path)){
	mkdir(iconv("GBK","UTF-8",$save_path),0777,true); 
}
$name = $file['name'];

$true_name = $save_path.$name;
$upres = move_uploaded_file($file['tmp_name'],$true_name);   //Modify file storage location
if($upres){
	$data['headimg'] = $true_name;
	echo json_encode(array('status'=>1,'data'=>$data));
}else{
	echo json_encode(array('status'=>0,'data'=>'upload error'));
}

Tags: PHP Javascript JSON

Posted on Thu, 21 May 2020 12:37:40 -0400 by fean0r