Reputation: 359
I use the code from talkerscode.com to implement file upload using drag and drop. The code is working. Now I would like to add additional input value during in the same ajax post. I add an input tag called "user_id" in the following html code. And I append the element into the formdata object. After the change drag and drop upload still work, but the PHP code complain the $_POST["user_id"] is not defined. Here is my code. Please help!
<html>
<!-- code original from talkerscode.com -->
<head>
<link rel="stylesheet" type="text/css" href="upload_style.css">
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="wrapper">
<input type="text" name="user_id", id="user_id" value="1228">
<input type="file">
<div id="drop-area">
<h3 class="drop-text">Drag and Drop Images Here</h3>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function()
{
$("#drop-area").on('dragenter', function (e){
e.preventDefault();
$(this).css('background', '#BBD5B8');
});
$("#drop-area").on('dragover', function (e){
e.preventDefault();
});
$("#drop-area").on('drop', function (e){
$(this).css('background', '#D8F9D3');
e.preventDefault();
var image = e.originalEvent.dataTransfer.files;
createFormData(image);
});
});
function createFormData(image)
{
var formImage = new FormData();
formImage.append('userImage', image[0]);
formData.append('user_id', $('#user_id').val());
uploadFormData(formImage);
}
function uploadFormData(formData)
{
$.ajax({
url: "upload_image.php",
type: "POST",
data: formData,
contentType:false,
cache: false,
processData: false,
success: function(data){
$('#drop-area').html(data);
}});
}
</script>
----------------PHP code -------------------
<?php
if(is_array($_FILES))
{
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$sourcePath = $_FILES['userImage']['tmp_name'];
$targetPath = "images/".$_FILES['userImage']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
?>
<img src="<?php echo $targetPath; ?>">
<p> user_id = <?php echo $_POST["user_id"] ?> </p>
<?php
exit();
}
}
}
?>
-----------------------------------------------
Upvotes: 0
Views: 3503
Reputation: 3407
function createFormData(image) {
var formImage = new FormData();
formImage.append('userImage', image[0]);
formData.append('user_id', $('#user_id').val()); //change formData to formImage
uploadFormData(formImage);
}
From:
formData.append('user_id', $('#user_id').val());
to:
formImage.append('user_id', $('#user_id').val());
Upvotes: 1