Can't send file with ajax to php file - javascript

I am having a problem with receiving File Data.
This is my HTML FORM:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Upload</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript" src="General.js"></script>
</head>
<body>
<form method="post" enctype="multipart/form-data" id="Form" action="upload.php">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="submit" type="submit" class="box" id="submit" value=" Upload "></td>
</tr>
</table>
</form>
As you can see it sends us to the file General.js
$(document).ready(function (e){
$("#Form").on('submit',(function(e){
e.preventDefault();
var formData = new FormData(document.getElementById('userfile'));
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "uploader.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(callback){
alert(callback);
}
});
return false;
})
);
});
and the php page that need to recieve this:
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
Everything works fine, but the problem is when i send the data to the php file, it doesn't receive it as it should. Maybe i need to use some addition things?
Because the name of the file and the size and everything is empty.
EDIT:
$(document).ready(function(){
$("#submit").click(function(){
var formData = new FormData($('form')[0]);
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "uploader.php",
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(callback){
alert(callback);
}
});
return false;
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
Also tried this code, but still it doesn't send the right information to the page. I am getting on the uploader.php page an error that says that the name of the file is empty, what means that maybe i don't receive it good or it didn't send at all.

Try using this...
$(document).ready(function (e) {
$("#Form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "uploader.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
console.log(data);
}
});
}));
});

change
var formData = new FormData(document.getElementById('Form'));
to
var fd = new FormData();
fd.append("userfile", document.getElementById('userfile').value);

Related

Uploading a file from a bootstrap modal using ajax

I am attempting to upload a file to a server from a bootstrap modal window, using ajax.
The modal html is
<div class="modal-body">
<div>
<form class="form" role="form" id="attachform" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit" class="btn btn-primary">Upload</button>
</form>
</div>
</div>
The Javascript
$("#attachform").on('submit',function(event){
event.preventDefault();
var postData = new FormData($("#attachform")[0]);
console.log(postData);
$.ajax({
url: "attachment.php",
type: "POST",
data: data,
processData: false, // tell jQuery not to process the data
contentType: false
}).done(function(msg) {
console.log(msg);
$('#myAttachModal').modal('hide');
});
});
});
The PHP server code
print_r($_POST);
print_r($_FILES);
I am not seeing anything in the $_FILES array when I run this.
Any suggestions?
Change the data value in your Ajax post to postData. postData contains the form data.
Change this section
data: data,
To
data: postData,//this contains the form data
You just need to change the data : data kew value inside the
$.ajax({
data : postData,
});
$.ajax({
url: "attachment.php",
type: "POST",
data: postData,
processData: false, // tell jQuery not to process the data
contentType: false
}).done(function(msg) {
console.log(msg);
$('#myAttachModal').modal('hide');
});
});
});

Uploading data and files in one form using Ajax PHP?

I'm using jQuery and Ajax for my forms to submit data and files but I'm not sure how to send both data and files in one form?
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
I was planning to use FormData as below
var formData = new FormData($(this)[0]);
but figured out that it does not work in IE<10 and which is not accepted. Is there any other approach for same?
This block should work for you.
$.ajax({
url: 'url',
type: 'POST',
async: true,
dataType: "json",
data: $('#data').serializeArray(),
error: function (a, b, c) { onError(a, b, c, parameters); },
success: function (data) { onSuccess(data, parameters); }
});
You can do like this in php instead of using form data,
Serialize you form data and send through ajax, like,
$.ajax({
type: 'post',
url: 'post.php',
data: $('#form').serialize(),
success: function () {
}
});
});
using $('#form').serialize() you can send your all form data to php.
I hope it helps,
function savedata(){
var vacancy_desc = CKEDITOR.instances['vacancy_desc'].getData();
var file_data = $('#fileupload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('vacancy_records',vacancy_records);
form_data.append('vacancy_desc',vacancy_desc);
$.ajax({
url:pathname,
method:"POST",
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data:form_data,
cache:false,
success:function(datas){
alert('Updated successfully !');
return false;
}
});
}

Image Upload to PHP Via Ajax

I am trying to create an image upload field in my application based on this question:
Send FormData and String Data Together Through JQuery AJAX?
and this tutorial:
http://www.formget.com/ajax-image-upload-php/
I have heard it is quite difficult, this is what i have tried.
HTML
<form method="POST" action="" id="logo_upload">
<input type="file" name="logo_location" id="logo_location" enctype="multipart/form-data">
<button type="submit" name="file_test" id="file_test">Test Upload</button>
</form>
JQuery
$('#logo_upload').submit(function(e) {
e.preventDefault();
var formData = new FormData();
var file_data = $('#logo_location')[0].files[0];
formData.append("file", file_data[0]);
$.ajax({
url: "../../../controllers/ajax_controller.php?action=image_upload",
type: 'POST',
data: formData ,
cache: false,
contentType: false,
processData: false,
id: id
});
});
PHP
var_dump($_FILES);
var_dump($_POST);
As you can see, I haven't got to the uploading side of things yet.
Result
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=0)</i>
<i><font color='#888a85'>empty</font></i>
</pre>
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=0)</i>
<i><font color='#888a85'>empty</font></i>
</pre>
I can't see what i am doing wrong, I am getting a result so it is getting to the right place, can anyone point me in the right direction?
EDIT: added #logo_upload in form
var file_data = $('#logo_location')[0].files[0];
EDIT: replaced data with formData variable
EDIT: added attribute: enctype="multipart/form-data"
New Result:
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=1)</i>
'file' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'undefined'</font> <i>(length=9)</i>
</pre>
You're appending file_data[0] to the formdata object, file_data is the file not an array, use file_data.
$('#logo_upload').submit(function(e) {
e.preventDefault();
var formData = new FormData();
var file_data = $('#logo_location')[0].files[0];
formData.append("file", file_data);
$.ajax({
url: "../../../controllers/ajax_controller.php?action=image_upload",
type: 'POST',
data: formData ,
contentType: false,
processData: false,
success: function(data){
console.log(data);
}
});
});
also you can instantiate the form data object with the form in question instead of doing the append.
$('#logo_upload').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
...
I don't see logo_upload id in your form.
When uploading a file enctype="multipart/form-data" is must in form attributes.
data parameter in your ajax getting a variable i.e. not defined. Look at your reference link once again.
Hope this would help you
You are passing wrong variable here and you are not defining success in your ajax request:
$('#logo_upload').submit(function(e) {
e.preventDefault();
var formData = new FormData($('#your_form_id')[0]);
$.ajax({
url: "../../../controllers/ajax_controller.php?action=image_upload",
type: 'POST',
data: formData,
success: function(result){
alert(result);
}
cache: false,
contentType: false,
processData: false
});
});

Spring Boot and jQuery file upload : Unsupported media type

I am trying to upload a csv file with spring boot 1.2.0 REST controller and jQuery ajax. When I send the post request, I keep getting 415:Unsupported Media type error. Here is my form:
<form id="upload_form">
<div id="message">
</div>
<br/>
<div class="row" id="upload-file-div" style="display: none">
<div class='col-sm-3'>
<label>Select File</label>
<input type="file" name="file">
</div>
<div class='col-sm-3'>
<input type="button" id="file-upload" class="btn btn-primary" value="Upload" onclick="uploadFile()"/>
</div>
</div>
</form>
Here is my method to upload file:
function uploadFile(){
var response = api.uploadCSV($("#upload_form"));
if(response.status === 'OK'){
$("#message").css('color', 'green');
}else{
$("#message").css('color', 'red');
}
$("#message").html(response.message);
}
Here is the actual jQuery POST:
upload: function (url, form, ignoreSuccess) {
var response = null;
if (!this.validate(form)) {
var array = form.serializeArray();
alert(array);
var formData = new FormData(form);
console.warn(formData);
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
cache: false,
contentType: false,
processData: false,
async: false,
beforeSend: function (request) {
if (api.getSession() !== null) {
request.setRequestHeader("Authorization", "Bearer " + api.getSession().bearer);
}
},
success: function () {}
}).done(function (msg) {
response = msg;
});
}
return response;
}
Following is my controller:
#RequestMapping(consumes = "multipart/form-data", method = RequestMethod.POST,
value = "/upload/twitter", produces = MediaType.APPLICATION_JSON_VALUE)
public Response<String> uploadCsv(CsvUploadModel form) {
//Code
}
I have both MultipartConfigElement and MultipartResolver annotated in my spring boot class. I am using spring boot 1.2.0. When I send the post request with PostMan (chrome extension), it works as expected. However, when I try the above jquery code, it keeps throwing unsupported media type error.
Following things I have tried:
Playing around content-type header, finally I have set the contentType to false.
Using form.serializeArray(), iterating over it and appending individual elements into formData.
Sending the form object instead of form data.
Can anyone please help me with this? Thanks in advance.
You can append your file input in your formData; the following changes needs to be made:
This:
<input type="file" name="file">
Should be:
<input type="file" name="file" id="file">
And in your ajax code, this:
var formData = new FormData(form);
console.warn(formData);
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
Should be:
var formData = new FormData();
formData.add("file",$('#file')[0].files)
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
Or:
var formData = new FormData(form[0]);
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,

AJAX formdata POST submit working in IE9/Chrome but not in Firefox

I have some AJAX script that submits a form and then updates the web page.
My Code:
HTML:
<form action='jobs.php' method='post' name='editUpdate' enctype='multipart/form-data' id="form-add">
<hr />
<textarea name='description' id="title" class="text1" placeholder="Add Update" cols='100' rows='5'></textarea>
<input type="submit" name='action' id="submit" value="Save Update"></input>
</form>
AJAX:
<script>
$('#form-add').submit(function(e){
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData(this);
var prependbdDiv = $('#prependbody');
$.ajax({
url: formURL,
type: 'POST',
data: formData,
dataType: "json",
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(response) {
if(response.success == "1"){
prependbdDiv.prepend("<tr><td>"+response.datetime+"</td><td>"+response.updatedesc+"</td></tr>");
$('#title').val('');
$("#form-add").fadeToggle();
}
},
error: function(response)
{
alert("ERROR");
},
});
e.preventDefault();
});
</script>
This seems to have resolved my issue:
Submiting a form with Ajax by using FormData on Firefox and IE10+
I am curious why this is the case or is it bad programming on my behalf?
Also when using FireBug the post data does not appear similar to that of the post data from a standard HTML form. IE, with the ajax post using formdata FireBug lists no "Parts" section under the POST details.
Thanks for your help!

Categories

Resources