files do not post when javascript submits form - javascript

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
})

Related

send uploaded files and inputs data with ajax

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

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/

jQuery: submit form on change

I'm trying to submit a form with a field element when a user clicks a button. I'm using the change function, which is called after a file has been chosen. The problem is that the form data is submitted without the field data. How can I make it submit the form after the field data is set?
The below code works fine if I call it with submit instead of change.
<form method="POST" action="public/index.php/students/edit/49" accept-charset="UTF-8" id="fileform" enctype="multipart/form-data">
<input type="button" onclick="document.getElementById('fileupload').click(); return false;" value="UPLOAD CV / RESUME" class="add" />
<input type="file" id="fileupload" style="visibility: hidden;" />
</form>
<script>
$('#fileupload').change(function()
{
var formData = new FormData($(this)[0]);
var request = $.ajax({
type: "POST",
processData: false,
contentType: false,
url: "{{URL::action('StudentController#addDocument')}}",
data: formData,
});
request.done(function( msg ) {
console.log( msg );
});
request.fail(function( jqXHR, textStatus ) {
console.log(textStatus );
});
});
</script>
You can try
$.fn.serializefiles = function() {
var obj = $(this);
/* ADD FILE TO PARAM AJAX */
var formData = new FormData();
$.each($(obj).find("input[type='file']"), function(i, tag) {
$.each($(tag)[0].files, function(i, file) {
formData.append(tag.name, file);
});
});
var params = $(obj).serializeArray();
$.each(params, function (i, val) {
formData.append(val.name, val.value);
});
return formData;
};
then in function ajax
var request = $.ajax({
type: "POST",
processData: false,
contentType: false,
url: "{{URL::action('StudentController#addDocument')}}",
data: $('#fileform').serializefiles(),
});
You want to upload a file or some files by ajax, you have to write a function above
this in $('#fileupload').change( ... ) refers to input element, formData expects a form element, try this:
$('#fileupload').change(function () {
var formData = new FormData(this.form);
...
});
you also need to add name attribute to your file input.
Request then looks like:
...
Content-Disposition: form-data; name="file"; filename="FILE_NAME"
Content-Type: CONTENT_TYPE
...

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.

How to pass Joomla form data via Ajax call to controller function

In my Joomla 3.3 form I inserted an ajax script to update some form fields dynamically.
...mainpart of the script is
formdata = new FormData();
jQuery.ajax({
type: "POST",
dataType: "json",
timeout: 6000,
url: "index.php?option=com_mycomponent&task=component.save",
data: formdata,
......................
........
After firing the ajax script, $_POST is completely empty in the controller, and I cannot access important formdata.
Meanwhile I tried several ways, eg
formdata = new FormData($(this)[0]); => nothing happens
or
formdata = new FormData();
formdata = $(this)[0]; => nothing happens
or
formdata = new FormData();
form = $(this)[0];
formdata.append("jform", form) => this fills up my $_POST, but with value undefined
How can I pass my formdata (the jform object) to the controller via Ajax POST method?
Try to use serialize function of jQuery:
var formdata = jQuery( "#formid" ).serialize();
Here formid is id of form element. Hope this helps..
I recognized two problems!
1) The form is a subform, displayed in a tab. Therefore not the id of the subform should be assigned in the script. You should assign the id of the main form
2) The ajax parameter "contentType: false" should be eliminated
With this parameter the ajax call will do its job!
ajax script:
$document->addScriptDeclaration('
jQuery(document).ready(function () {
jQuery("#btn1").click(function() {
alert ("Button");
var formdata = jQuery( "#main-form" ).serialize();
jQuery.ajax({
type: "POST",
dataType: "json",
timeout: 6000,
url: "index.php?option=com_mycomponent&task=component.save",
data: formdata,
processData: false,
success:function(result) {
jQuery.each(result.data, function(i, item) {
..........
});
}
});
return false;
});
});
');
html:
form action="<?php echo JRoute::_('index.php?option=com_mycomponent'); ?>"
method="post" name="market_photos" id="subform-form" class="form-validate" enctype="multipart/form-data">
<fieldset class="form-horizontal">
<legend><?php echo JText::_('COM_MYCOMPONENT'); ?></legend>
<ul class="adminformlist">
<table id="table1">
<tbody>
</tbody>
</table>
</ul>
</fieldset>
<div class="span5">
<fieldset class="form-horizontal">
<legend><?php echo JText::_('COM_MYCOMPONENT'); ?></legend>
<div class="control-group">
......
....
I hope these parts give a better insight!

Categories