I'm new to web development and I'm making image upload in PHP with Ajax. I am having a problem in receiving ajax send data in PHP. I spend a few hours in finding the solution but I can't.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<h2 id="msg"></h2>
<input type="file" name="img" id="img">
<button onclick="uploadImg();" type="button">Upload</button>
</body>
</html>
Javascript
function uploadImg() {
var img = document.getElementById('img').value;
var data = "data=img";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "upload.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("msg").innerHTML = this.responseText;
}
};
xmlhttp.send(data);
}
PHP
<?php
$file = $_FILES['data']['tmp_name'];
$uploadTo = "uploads/";
$name = $_FILES['data']['name'];
if( move_uploaded_file($file, $uploadTo.$name) ) {
echo "SUCCESS";
} else {
echo "ERROR";
}
?>