How to send/upload file information to php using jquery ajax?
info is the file to be uploaded.
$.ajax({
type: "POST",
url: url,
data: data, /* data from input file to upload it */
async: false,
beforeSend: function() {
},
complete: function() {
},
cache: false,
success: callback,
error: function(error) {
alert("Some problems have occured. Please try again later: " + error);
}
});
<form id="product-form" action="javascript: product();" enctype="multipart/form-data">
<input type="file" name="img" />
Submit
</form>
You cannot do this with jQuery alone. You need to either use a jQuery plugin such as Uploadify or use HTML 5. Please note that not all browsers support HTML 5 at this time, so jQuery Uploadify may be the better choice.
Related
I have a standard HTML form that asks the user for a file to upload.
<form id="uploadForm" action="http://localhost:5000/api/collection/csv" method="post" enctype="multipart/form-data" >
<div class="form-group">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="files" multiple />
</div>
</div>
</form>
This alone would work fine, however the API requires an Authorization Header that looks something like this:
Authorization: Bearer eyJhb.......
The web API is an ASP.Net Web API that is expecting the header, the content type multipart/form-data, and to have proper webkit- boundary as part of the POST submission.
I've searched online and it seems there's no way to add a custom header to a form submission. Is there another way to upload this file properly with the custom header?
The answer that worked for me was what #Musa suggested in the comments.
I needed to use jQuery's form submit event so I can create a FormData object and submit that using ajax.
The solution in this case was this:
$("#uploadForm").on( "submit", function( event ) {
event.preventDefault();
var form = $(this)[0];
var postData = new FormData(form);
$.ajax({
type: "POST",
url: "http://localhost:5000/api/collection/csv",
beforeSend: function(request) {
//ADD CUSTOM HEADER HERE
request.setRequestHeader("Authorization", "Bearer " + idToken);
},
data: postData,
contentType: false, //THIS IS REQUIRED
processData: false, //THIS IS REQUIRED
success: function(data){
//Handle success here
resolve(data);
},
error: function (xhr, textStatus, error) {
//Handle error
reject(error);
}
});
});
I'm not sure why contentType: false, processData: false was required, but it wouldn't work without it.
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 5 years ago.
I create jersey REST server and receive file upload.
This is the tutorial I follwed: https://gist.github.com/aitoroses/4f7a2b197b732a6a691d
Everything works fine when I try to test the server with Postman. I chose Body, form-data, key: file, value: my picture jpeg
What I try to do is to upload file using form html and jquery
Here is my form
<form>
<input id="imgFile" type="file" accept="image/*" value="Add file">
<input id="buttonPostReview" class="buttonSend" type="submit" value="Submit">
</form>
and here is my jquery
var postFile = function(e) {
e.preventDefault();
var imgFile = $('#imgFile').val();
var upLoalImgUrl = endPointUrl + 'webresources/photo';
console.log(imgFile);
console.log('uploading..');
$.ajax({
type: "POST",
url: upLoalImgUrl,
data: imgFile,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (returnData) {
console.log(returnData);
alert("Data Uploaded: ");
}
});
}
But I got error 415 - Unsupported Media Type
Can you show me how to upload file using jquery? I try to do some search but I can find the way to do this
$(...).val() doesn't get a file from a file input, it just returns the name of the file. You need to do $("#imgFile")[0].files[0] and send the file with FormData:
var data = new FormData();
data.append('file', $("#imgFile")[0].files[0]);
$.ajax({ data: data, ... });
I have a basic messaging service on a web Node / Express web app, and I'm trying to submit the form via Ajax, using the FormData object.
If I submit the form without AJAX, then everything works fine, but with AJAX the req.body. are all undefined.
On the server, I need to look for the data somewhere other than req.body when using AJAX??
Creating the FormData object:
var ajaxData = new FormData;
ajaxData.append('newMessage', $('.new-message').val()) // I've console.logged these, and their values are correct
ajaxData.append('senderId', $('[name="senderId"]').val())
ajaxData.append('senderName', $('[name="senderName"]').val())// I've console.logged these, and their values are correct
ajaxData.append('recipientId', $('[name="recipientId"]').val())
ajaxData.append('recipientName', $('[name="recipientName"]').val())// I've console.logged these, and their values are correct
And this is the POST request:
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: ajaxData,
dataType: false,
cache: false,
contentType: false,
processData: false,
complete: function() {
console.log('message created');
},
success: function(data) {
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(errorThrown);
}
});
EDIT
Thanks to G. Mansour for his answers below. In case anyone else gets here, the issue was the line:
contentType: false,
I tried this line at some point, which also doesn't work
contentType: 'application/json',
But when I remove the line entirely, everything is working as normal... If anyone can tell me why this line was breaking everything, I'd be interested to know.
This is the html part
<form id="form" action="" method="post">
<input type="text" name="msgID" id="msgID">
<input type="text" name="senderId" id="senderId">
<input type="text" name="senderName" id="senderName">
<input type="text" name="recipientId" id="recipientId">
<input type="text" name="recipientName" id="recipientName">
<input type="submit" name="dsq" value="dsqdsq">
</form>
this is the JavaScript part
<script type="text/javascript">
$(document).ready(function(){
$("#form").submit(function(){
$.ajax({
url: "test.php",
data: $("#form").serialize(),
type: "POST",
dataType: 'json',
success: function (e) {
console.log(JSON.stringify(e));
},
error:function(e){
console.log(JSON.stringify(e));
}
});
return false;
});
});
</script>
And this is the php code
<?php
die(json_encode(array("status"=>true)));
?>
Hope that will helps you.
I checked your code it says that's
Illegal invocation
So i'll give a solution you can use
data: $form.serialize(),
dataType: 'json',
And then you can catch your returned result by
console.log(JSON.stringify(e));
Wish that helps. If you have some errors i can help you.
I have a form, with a file input, that submits just fine when I use the default action to submit the form. But, when I use JQuery and AJAX to make the call to the PHP file, it does not seem to get the file. Is there something that I need to add for sending files through JQUERY/AJAX?
My HTML:
<form id="photo-form" enctype="multipart/form-data" method="post" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000"/>
<input type="file" class="upload-input" name="upload-new-input" autocomplete="off"/>
<input type="submit" name="submit" value="submit/>
</form>
My JQuery:
$(document).ready(function() {
$("#photo-form").submit(function(e) {
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "uploadcover.php",
data: dataString,
async: false,
success: function(data) {
alert(data);
}
});
});
});
You can use FormData to upload file with data
Here is sample code
JQuery
$("#photo-form").submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "uploadcover.php",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data) {
alert(data);
}
});
return false;
})
You can get it on PHP
PHP CODE
$Img = $_FILES['upload-new-input'];
You can see tutorial Uploading files with jquery ajax
Hope It helps you :)
You cannot access file directly.
You can use a plugin, to do this for you, i.e. https://github.com/blueimp/jQuery-File-Upload
Also, in html5 it is possible to access a file from file input as a blob. You can than send it using formData.
More info here: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
HTML
<input type="file" id="file1" />
SCRIPT
file=$("#file1");
$.ajax({
type: "POST",
url: "Allcammand.aspx?cmd=EnterProduct&idCompany="+getParam("idCompany"),
type:"post",
data: {
file: file
},
async: false ,
success: function(response){
},
error:function(xhr, ajaxOptions, thrownError){alert(xhr.responseText); ShowMessage("خطا در انتقال اطلاعات شرکت","fail");}
});
This is true whether the file transfer.
in Allcammand.aspx how can get file?????
Uploading files via AJAX is a complex process that you probably aren't going to want to write yourself. I'd recommend using something like this: http://jquery.malsup.com/form/