I'm trying to send input file
and input text
through ajax. Because I'll add this feature to my existing function that has plenty of other variables I cannot simply use sending the entire Form
like the one used here
Uploading both data and files in one form using Ajax?
This is the basic gist of it
My HTML
<input type='text' name='text' id='text'>
<input type='file' name='media' type="file" / id='media'>
<input type="button" value="Upload" name='submit'/>
My Ajax
$(":button").click(function(){
var myFormData = new FormData();
var media = document.getElementById('media');
var variable = 'foo';
myFormData.append('pictureFile', media.files[0]);
var text = $("#text").val();
$.ajax({
type: 'POST',
url: 'upload.php',
data:
{
pictureFile: myFormData,
text: text,
var: variable,
},
cache: false,
success: function (data) {
alert(data);
},
processData: false,
contentType: false,
});
});
PHP
include_once ("connection.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$temp_name = $_FILES['pictureFile']['name'];
$pic_type = $_FILES['pictureFile']['type'];
$pic_temp = $_FILES['pictureFile']['tmp_name'];
$pic_path = "images/";
move_uploaded_file($pic_temp,'images/'.$temp_name);
}
So as shown in my code I need a way to send those var media
, var text
and var variable
from data:{},
to upload.php
You can achieve that by using append
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Jquery Ajax File Upload</title>
</head>
<body>
<input type='text' name='text' id='text'>
<input type="file" name="media" id="media">
<div class="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#media').change(function(e){
var file = this.files[0];
var form = new FormData();
form.append('media', file);
form.append('text', $('#text').val());
$.ajax({
url : "upload.php",
type: "POST",
cache: false,
contentType: false,
processData: false,
data : form,
success: function(response){
$('.result').html(response.html)
}
});
});
});
</script>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With