Hichame Zbaidi
Hichame Zbaidi

Reputation: 9

upload file by ajax, javascript,php

please i want to upload file by ajax and javascript,php without refresh the page : my idea is to send file by ajax xmlhttp.send(file); and get the file in script php, but i don't know how to do this uing function record

function record(elem){
	    
	 }
<td style='font-size:11px;'><span id='confirm1 $id'>Confirm : <input id='confirm1' onchange='record(this.id);' style='font-size:9px; height:27px; width:134px;' type='file' name='confirm1' /></td>

Upvotes: 0

Views: 58

Answers (2)

Hichame Zbaidi
Hichame Zbaidi

Reputation: 9

the problem is how to get the file in script php : $_files['thefile']:

function record(elem){
		var quelr=elem;
		var file1 = document.getElementById(quelr);
		var path = file1.value;
		var file = file1.files[0];
		var formData = new FormData();
		formData.append("thefile", file);

		
	var startIndex = (path.indexOf('\\') >= 0 ? path.lastIndexOf('\\') : path.lastIndexOf('/'));
	var filename = path.substring(startIndex);
	if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
		filename = filename.substring(1);
	}
	alert(filename);
	         xmlhttp=new XMLHttpRequest();
			 alert("mehdi");
		     xmlhttp.open("POST","record.php",true);
			 alert("mehdi");
			 xmlhttp.setRequestHeader("enctype","multipart/form-data");
			 xmlhttp.send(formData);
		     document.getElementById(quelr+" "+id).innerHTML=xmlhttp.responseText;
	 }

Upvotes: 0

iridian
iridian

Reputation: 709

You're probably looking for something like the FormData API:

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files

An easier method may be to just use an iframe.

Upvotes: 1

Related Questions