I want to upload file to server using AJAX and PHP. Here is what I've tried so far but it is not working for me. The server throws this error:- Notice: Undefined index: file in C:\xampp\htdocs\authentication\test.php on line 3 Notice: Undefined index: file in C:\xampp\htdocs\authentication\test.php on line 7 Notice: Undefined index: file in C:\xampp\htdocs\authentication\test.php on line 7 Client side code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Generator</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery-2.1.4.js"></script>
<script type="text/javascript">
function valid(){
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'test.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('#result').html(data); // display response from the PHP script, if any
}
});
}
</script>
</head>
<body>
<div id='result'></div>
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick='valid()'>Upload</button>
</body>
</html>
And here is client side code, test.php:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name'])){
echo "file uploaded";
}
}
?>