Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  126] [ 2]  / answers: 1 / hits: 18006  / 7 Years ago, tue, january 31, 2017, 12:00:00

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


More From » php

 Answers
96

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>

[#59142] Saturday, January 28, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
longd

Total Points: 616
Total Questions: 110
Total Answers: 101

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;