send uploaded files and inputs data with ajax - javascript

I'm trying to upload files with datas using ajax.
here is my html form :
<body>
<input type="text" id="name" value="test" />
<input type="file" id="pic" accept="image/*" />
<input id = "submit" type="submit" />
</body>
when I send the uploaded file alone with ajax it is working using new FormData();
var file_data = $('#pic').prop('files');
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(php_script_response){
alert(php_script_response);
}
});
but Idon't know how to send the input 'name' with Data
var DATA = 'name='+name;
$.ajax({
url: "test.php",
type: "post",
data: DATA,
success: function (response) {
console.log($response);
},
});
Thanks

First of all you should include form tags such as the following example.
<form id="uploadForm" enctype="multipart/form-data" action="http://yourdomain.com/upload" method="post" name="uploadForm" novalidate>
<input type="text" id="name" value="test" />
<input type="file" id="pic" accept="image/*" />
<input id = "submit" type="submit" />
</form>
Then you can send all of the form data using code such as the following:
var form = $('#uploadForm')[0];
var form_data = new FormData(form);
To answer your specific question about sending the value of only the text field with ID "name", simply use the following line:
var DATA = 'name=' + $('#name').val();

var name = $("#name").val();
form_data.append('name', name);
Maybe it's wrong, please try

Related

jQuery FormData and files

I'm attempting to do ajax file upload. When i check the variable form_data it is blank?
<form action='ajax_image_upload/process.php' method='post' enctype='multipart/form-data' class='upload_form'>
<textarea name='description' placeholder='Type Default Video Description'></textarea>
<span>
Channel Image: <input type='file' name='image' />
</span>
<input name='__submit__' type='submit' value='Upload'/>
</form>
var container = $(".upload_form");
var form_data = new FormData();
form_data.append('image', container.find("form > span").children("input[name='image']"));
var post_url = container.children("form").attr("action"); //get action URL of form
//jQuery Ajax to Post form data
$.ajax({
url : post_url,
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
mimeType: "multipart/form-data"
}).done(function(res){
});
How can I solve this?
The issue is because you need to append the binary data from the file input to the FormData, not the jQuery object. Try this:
var fileData = container.find("form > span").children("input[name='image']")[0].files[0];
form_data.append('image', fileData);
Obviously, if there are multiple inputs, or multiple files within the input, you'll need to loop through them and append them individually.

file upload with formData returns undefined file array

im getting undefined from print_r($_POST), it's posting on the same php page.
Array ( [file] => undefined )
Edited - added part where it calls the upload_banner function
HTML
<form enctype="multipart/form-data" id="banner_form" class="form-horizontal" role="form" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input id="file" name="file" type="file" class="filestyle" accept="image/jpeg,image/gif,image/png">
</form>
JS
$('#submit_btn').click(function(e){
e.preventDefault();
var date = document.getElementById('datepicker').value;
var title = document.getElementById('title').value;
var content = document.getElementsByClassName('note-editable')[0];
if(date == "" || title == "") {
alert("Please fill in the required fields");
return false;
}
else {
var cfm = confirm("Confirm Submit Changes?");
if(cfm === true)
{
var editarea = content.innerHTML;
$.post ("functions/add_upcoming.php",{date: date,title: title,sm_content: editarea},
function(data) {
});
upload_banner();
}
else
{
return false;
}
}
});
function upload_banner() {
var form_data = new FormData($('#banner_form')[0]);
form_data.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: "upcomingevents.php?p=73",
contentType: false,
processData: false,
dataType: 'json',
data: form_data,
type: 'post',
success: function(data) { },
contentType: false,
processData: false
});
}
json as datatype cause im returning arrays from php side, did not post additional code cause im already getting issue at the file upload part
PHP
if(isset($_POST['file'])) {
print_r($_POST);
exit();
}
am i doing anything wrong here?
The FormData is set up incorrectly, should be :
var form_data = new FormData( );
form_data.append('file', $('input[type=file]')[0].files[0]);
Are you sure the url refered by the ajax is correct?
Why is there query param (?p=73) as you're doing post and not get.
Finaly, try to print the response through
success: function(data) { alert(JSON.stringify(data))},
You're function isn't even being called considering you don't have the submit button for the handler to run.
It should be like:
<form enctype="multipart/form-data" id="banner_form" class="form-horizontal" role="form" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input id="file" name="file" type="file" class="filestyle" accept="image/jpeg,image/gif,image/png">
<input type="submit" id="submit_btn"/>
</form>
Also you have a syntax error in your JS, there is no need for the second set of }); to close the click handler.
JSFiddle:
https://jsfiddle.net/sggf82am/2/

files do not post when javascript submits form

I have an image upload form which is submitted by a javascript but the file data is not being submitted. I have looked at examples of how to fix this with ajax but cannot find any examples that address it with the javascript submit that I am using.
<td>New Photo<br>
<div id="editphoto">
<form id="editphoto" enctype="multipart/form-data" method="post" action="editphoto.php">
<input type="hidden" name="employeeid" value="<?php echo $listing[$k]["employeeid"] ?>">
<input type="file" name="file2">
<input type="submit" value="Submit">
</form></div></td>
<script>
$('#editphoto form').submit(function(){
var data=$(this).serialize();
$.post('editphoto.php', data , function(returnData){
$('#editphoto').html( returnData)
})
return false; // stops browser from doing default submit process
});
</script>
Files cannot be serialized. You can use FormData To submit a file using jQuery.
$('#editphoto form').submit(function(){
var formData = new FormData();
formData.append('file2', $('input[type=file]')[0].files[0]);
// append other form-data to formData object
var otherData = $(this).serialize();
$.each( otherData , function(key, field){
formData.append(field.name, field.value);
});
// post form
$.ajax({
url: 'editphoto.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function( returnData ) {
$('#editphoto').html( returnData)
}
});
return false; // stops browser from doing default submit process
})

formdata with jquery not working,server returns empty string

I have gone through most of the responses from previous similar questions and tried, yet same result. There is no server error, data fields received by server are null.I am using form data.
$("#sbtn").onclick( function(){
var url = "php/add.php";
var fd = new FormData();
fd.append('file',files[0]);
fd.append('type',"music");
fd.append('username', $("input[name=username]").val());
$.ajax({
type :"POST",
url : url,
data : fd,
contentType: false,
processData: false,
success : function(resp){ alert("server response : " + resp );}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form onsubmit="return false;">
<label for="username">Name</label>
<input type="text" size="10" name="username">
<input type="file" required />
<input type="submit" value="add" id="sbtn"/>
</form>

Formdata append file upload is not working in codelgniter,Getting error

All I am trying to do is upload files using ajax to my CodeIgniter based website.But i cannot get file field value in controller.I am getting message like "Undefined index: 'file_1'"
How to solve this issue?
Form
<form method="post" enctype="multipart/form-data">
<input type="file" id="file_1" name="file_1" value="" class="field1" />
<input type="button" onclick="up_img()" value="Upload" />
</form>
Javascript:
<script type="text/javascript">
function up_img()
{
formdata = false;
var imgfile = document.getElementById("file_1");
formdata = new FormData();
formdata.append("file_1",imgfile.files[0]);
$.ajax({
url: "<?php echo base_url(); ?>index.php/save_project_upload/",
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
}
Controller:
function save_project_upload()
{
echo $upfile_name = $_FILES['file_1']['name'];
}
If you do a print_r( $_FILES ) are you getting any content?
Also, be aware that this is not supported by IE8 and earlier.
You could also try to do:
var formData = new FormData($('#yourformID')[0]);
EDIT:
formData.append('file_1', $('input[id="file_1"]')[0].files[0]);
Might also solve your problem, by adding [0] to the DOM element.

Categories