Unable to upload file using AJAX - javascript

I am trying to upload a file through AJAX. I have searched over a lot but found examples using form submit only, but I can not use form submit. I have tried several examples but nothing reaches my server. When I tried this link, it worked but again it was through a form submission.
Here is the piece of code relevant to the context
JS Code
function _upload(filedata) {
$.ajax({
url: './myURI',
data: filedata,
type: 'POST',
contentType: 'multipart/form-data',
mimeType: 'multipart/form-data', //Property added in 1.5.1
success: function (data) {
alert(data);
}
});
}
$("#cpc-uploadBtn").click(function (evt) {
var data;
data = new FormData();
data.append('file', $('#cpc-upload')[0].files[0]);
_upload(data);
});
HTML Part
<input id="cpc-upload" name="file" type="file" />
<button id="cpc-uploadBtn" type="button">Upload</button>
Edit
Is there any other way to do this without using form submit and formdata?

Assuming that you are using Safari/FireFox (only those support FormData), you need to modify your $.ajax call:
$.ajax({
url: './myURI',
data: filedata,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
alert(data);
}
});
Seeting contentType option to false will force jQuery not to add a Content-Type header for you (otherwise the boundary string will be missing from it). Also the processData flag must be set to false so jQuery will not try to convert your FormData into a string.
Now if you know that your clients are using HTML5 you should try using new JavaScript File API - check following articles:
Working with files in JavaScript, Part 1: The Basics
Working with files in JavaScript, Part 2: FileReader
Working with files in JavaScript, Part 3: Progress events and errors
Working with files in JavaScript, Part 4: Object URLs
Working with files in JavaScript, Part 5: Blobs
In all other cases you are forced to use custom plugins, for example:
Uploadify
jQuery Form Plugin

I suppose currently FormData objects are only supported in Safari/Firefox, it has not been adopted by most of the browsers yet.
I recently struggled a lot finding ajax file uploader for asp.net and I am currently using this one in my project:
https://github.com/valums/file-uploader

there is a small alternative if you want to use
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing soinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
you can find the plugin here

Related

Upload a file with from vuejs app using ajax post

Does anyone know how to upload a file in a vuejs app and pass it to a php page using jquery's ajax function. Please for the love of all thats holy I need some help with this. I essentially want to do this but run it in a vuejs method. (the following script works outside of the method and the post and files array is set. but when placed in a method it no longer works. In other words the
$_FILES and $_POST array is not set) I would prefer to do this without axios or any other external libery other than jquery if possible. Does anyone know if you can even do this in vuejs?
$(document).ready(function(){
$('#addTemplateForm').on('submit', function(e){
e.preventDefault();
app.sub=true;
if(app.name!='' && app.thumbnailName!='' && app.renderTime!=''
&& app.textFieldCount!='' && app.selectedCategories.length!=0 && app.selectedKeywords.length!=0)
$.ajax({
url:'addTemplateBackend.php',
type:'POST',
dataType: 'json',
data: new FormData(this),
contentType: false,
processData: false,
error: function(data){
alert('error');
},
success: function(data){
alert('success');
console.log(data);
}
})
});
});
Please describe the error you are having. You can check your console and also use the Vue tool plugin extension for browsers so as to help you with trouble shooting.
PS: This was a mistake. Meant to be a comment not an answer

Bootstrap wysihtml5 show extra strings

I'm using bootstrap-wysihtml5 editor. On my web its working good. But when I send data from it to php using jquery it send some extra data. For example:
When I send this:
product two
It send the followings:
product+two%3Cbr%3E
My Bootstrap wysihtml5 configuration is here:
$('#form').wysihtml5({
image: false
});
And my jquery ajax code is here:
$.ajax({
url: "index.php",
type: 'POST',
dataType: 'html',
data: {
contentEdit: $('#form').serialize()
},
success: function(data) {
alert('something ...');
}
});
What is the procedure to avoid that?
actually the problem was that I have used multiple form in one page. Otherwise it works within a framework that means when we integrate the Bootstrap wysihtml5, it's embedded through an iframe. Ultimately I have solved the problem by using ckeditor. It is more flexible and easy to use. To easily use it you can follow its API documentation. Thanks to all.

Display PDF inline in browser using ajax

I know that this question is already asked many times by different ways. But still i am not able to figure out the answer. I mean i did not find a proper descriptive answer.
I use mpdf library to generate PDF. I post some data of hidden fields to a PHP script by means of ajax.
Following are the code snippets.
//ajax_file
$("#button_id").click(function(e){
var table_clone=$("#table_id").clone();
var tableData=table_clone.prop('outerHTML');//html for pdf generation
dataString='page='+tableData;
$.ajax({
type: 'POST',
url: 'pdfgenerator.php',
data: dataString,
cache: false,
success: function(response)
{
//what to do here in order to display pdf
},
error: function(............){
.
.
}
});
});
PHP Script
//pdfgenerator.php
<?php
include('../mpdf/mpdf.php');
if(/*checking post items are set*/)
{
//retriving post items
$mpdf=new mPDF('c','A4-L');
$mpdf->WriteHTML($tableData);
$mpdf->output('xyz.pdf','I');
exit;
}
?>
Following are my constraints
-> I don't want to save file permanently on server (which is possible by means of 'F' option in output()).
-> I have to display it in browser from where it can be downloaded.
PHP script works correctly if called without ajax. Hence it returns correct data but i am unable to display it in pdf inside the browser.
While searching for answers i found that it is not possible by means of ajax.
so is there any way around by doing something in PHP or javascript. Please provide a descriptive answer.
Thanks,
You can use this code
$.ajax({
type: 'POST',
url: 'pdfgenerator.php',
data: dataString,
cache: false,
success: function(response)
{
var tag ='<object width="400" height="500" type="application/pdf" data="'+xyz.pdf+'" id="show_obj1" class="obj"></object>';
$(#pdfdiv).html(tag);
},
error: function(............){
.
.
}
});
});
Here #pdfdiv in $(#pdfdiv).html(tag); is the id of the div in which you want to show the pdf

.ajaxSubmit from the jquery.form.js not working with data option

I am using the plugin jquery.form.js and I want to programmatically submit a form and include a file with it. The code and options I have set up with work with $.ajax but not .ajaxSubmit. According to the jquery.form.js documentation you can pass any standard $.ajax options to .ajaxSubmit but I can't seem to get it to work. I'd like to use .ajaxSubmit if possible so I can utilize some of the other features it offers.
$(document).ready(function() {
$('#file-form').submit(function(event) {
event.preventDefault();
var form = $("<form style='display:none;' method='post' action='video_upload.php' enctype='multipart/form-data'></form>");
var fd = new FormData();
fd.append('uploadedfile', $('#file')[0].files[0]);
var options = {
url: 'video_upload.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
beforeSend: function(xhr){
alert('start');
},
success: function(data){
alert(data);
}
};
$.ajax(options);
//form.ajaxSubmit(options);
return false;
});
});
Running $.ajax(options) works but form.ajaxSubmit(options) doesn't. What am I missing?
Thanks!
If you check the source code of the method ajaxSubmit - http://malsup.github.io/jquery.form.js you can see that the property data of the options is serialised/deserialised and converted several times. So most likely the content really submitted will be quite different from what happens in .ajax call. Later on the ajaxSubmit collects the files from form and submits them differently.
Basically, for me the specifying data while submitting with ajaxSubmit goes against the concept of this plugin, which is described as "The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process." Idiomatic way of using ajaxSubmit would be applying this method for the form with controls.

Submitting a form to a Rails server from jQuery using AJAX isn't working in IE11

I'm trying to upload some data from a from to a Rails server using AJAX. The form contains two text inputs and one file input. Here's what my submit event handler looks like:
$("form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
data: new FormData(this),
contentType: false,
processData: false
});
});
This works fine in every browser except IE. When I try to submit the form in IE, my Rails server spits out the following error:
Unexpected error while processing request: bad content body
/Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/multipart/parser.rb:117:in `get_current_head_and_filename_and_content_type_and_name_and_body'
/Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/multipart/parser.rb:19:in `block in parse'
/Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/multipart/parser.rb:17:in `loop'
/Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/multipart/parser.rb:17:in `parse'
/Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/multipart.rb:25:in `parse_multipart'
/Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/request.rb:377:in `parse_multipart'
/Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/request.rb:203:in `POST'
/Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/methodoverride.rb:26:in `method_override'
/Users/landonschropp/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/methodoverride.rb:14:in `call'
...
I'd appreciate any insights into why this might not be working.
This might be a bug with IE10/11's serializing of form data. According to a blog post, those versions of IE corrupt the request when the last checkable input is not checked.
[1] http://blog.yorkxin.org/posts/2014/02/06/ajax-with-formdata-is-broken-on-ie10-ie11
Is there a <script> tag in the new content? If so, try it without that bit. I've seen some versions of ie have troube with js updates containing that tag...
You can add a csrf token before making a AJAX call. something like
$(document).ready(function(){
$("form").on("submit", function(event) {
event.preventDefault();
set_csrf_token();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
data: new FormData(this),
contentType: false,
processData: false
});
});
function set_csrf_token() {
// for protectting from forgery and sending the x-csrf token
$.ajaxSetup({
beforeSend : function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
});
}
});
I assume you are uploading a file using the form . Using jQuery file upload it submit the form using a hidden iframe. some time IE change the file content type like .jpeg will be .pjpeg that also may can the issue.
Instead of using FormData, I used the jQuery Form Plugin, which fixed the problem.
$("form").on("submit", function(event) {
event.preventDefault();
$(this).ajaxSubmit();
});

Categories