2

I am trying to upload a file using jQuery's $.ajax function but didn't get any output. Somebody please help me to solve this. I don't know if this script is correct. My script is:

$.ajax({
  url:'newsup.php',
  data: "",
  type: 'POST',
  contentType:'multipart/form-data',
  dataType: 'json',
  catche: 'false',

  success:function(data6)
  {
    $("#disp").removeClass().addClass((data6.error=== false)? 'success':'error').html(data6.msg).fadeIn('fast');
    //dele();
    if($("#disp").hasClass('success'))
    {
      alert("success");
      setTimeout("$('#disp').fadeOut('slow')",3000);            
    }
  },

  error:function(XMLHttpRequest,textStatus,errorThrown)
  {
    $("#disp").removeClass().addClass('error').html("There was an <strong>"+errorThrown+"</strong> error due to  <strong>"+textStatus+" condition").fadeIn('fast');
  }              

});

Also I need help getting data from file uploading field using jQuery.

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
JOE
  • 489
  • 4
  • 7
  • 16
  • Look up plupload (http://www.plupload.com/) for an example of doing AJAX-style form uploading. Submitting a form with a file via normal post in a single page is very difficult without using an embedded iframe for submitting an invisible form. Plupload also integrates pretty well with jQuery (at least that was my experience). – Los Frijoles May 08 '12 at 04:41
  • Have you done any google for this? I hope plenty of useful results come. One of those http://www.phpletter.com/Demo/AjaxFileUpload-Demo/ – Selvakumar Ponnusamy May 08 '12 at 04:42
  • There is a popular and well tested jquery plugin if you okay to use one, https://github.com/blueimp/jQuery-File-Upload – Juzer Ali May 08 '12 at 05:01
  • catche ? , it should be "Cache" . may be typo mistake ? – Ravi Gadag May 08 '12 at 05:05
  • I not interested to use any of plugins. I just want a simplest solution for uploading file through $.ajax function. – JOE May 08 '12 at 05:06
  • I tried 'cache' but no change – JOE May 08 '12 at 05:16

8 Answers8

6

Please use plugin for this.
In my opinion this plugin is better solution for this.You don't need to remember all options etc.Just replace your 'ajax' to 'ajaxForm'.

Please read examples ,below
http://jquery.malsup.com/form/#ajaxForm

Oyeme
  • 11,088
  • 4
  • 42
  • 65
  • 1
    I love this plugin. I use it in every website I develop. There's no point wasting time AJAX'ing your form manually when this plugin does a darn good job of it. – Ayush May 08 '12 at 06:00
  • I tried malsups $ajaxForm plugin but i can't pass the data which i stored in a variable to `$ajaxForm()` function. It only works by getting data directly from form like `$('#myForm1').ajaxForm(options);` . How can i overcome this problem. – JOE May 15 '13 at 09:06
  • LIke below can i pass data stored in a data variable to the **ajaxForm** function? `var data="formdata=data"; $(document).ready(function() { var options={ Target: '#output1', url: url, data: data}; $('#myform1').ajaxForm(options); });` – JOE May 16 '13 at 04:40
  • @JOSEPHPAUL var data="formdata=data"; must be a global variable,because $(document).ready(function() {..} it means you are in different scope – Oyeme May 16 '13 at 09:36
  • Actualy i am not much good in jquery, if you don't mind can you please refer me an example – JOE May 16 '13 at 16:24
  • @JOSEPHPAUL just have a look http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/ – Oyeme May 19 '13 at 21:49
3

This is how I've done it. Use the FormData object.

Note: The odd syntax of the for statement is just setting "f" to the array[i] instance.

        $("#submit").click(function () {
            var formData = new FormData();
            for (var i = 0, f; f = fileArray[i]; i++) {
                formData.append("opmlFile", f);
            }
            $.ajax({
                url: "/Documents/SaveFiles/" + @Model,
                type: "POST",
                data: formData,
                cache: false,
                contentType: false,
                processData: false
            })
            .error(function (xhr, status, error) {
                $.notify(error, true);
            })
            .success(function (data, status, xhr) {
                $.notify("Success");
            });
        });

Unfortunately I don't recall which article I got this from, but it was someone else on Stack Overflow.

Fred
  • 1,344
  • 1
  • 11
  • 16
2

AJAX doesnt support file uploading. There are plugins like ajaxfileupload which basically creates a hidden form and uploads your file dynamically.

take a look here and read Oli's answer

Community
  • 1
  • 1
killebytes
  • 940
  • 1
  • 10
  • 24
  • I appreciate your interest in answering my question and thanks for your answer. – JOE May 08 '12 at 05:39
2

I'm using this and it's working fine:

  $('#btnUploadFile').on('click', function () {
                var data = new FormData();
                var files = $("#fileUpload").get(0).files;

                // Add the uploaded file content to the form data collection
                if (files.length > 0) {
                    data.append("upload", files[0]);
                }

                // Make Ajax request with the contentType = false, and procesDate = false
                var ajaxRequest = $.ajax({
                    type: "POST",
                    url: "/api/documents",
                    contentType: false,
                    processData: false,
                    data: data,

                    error: function (xhr, status, error) {
                        console.log(xhr);
                        console.log(status);
                        console.log(error);
                        console.log(data);
                    }
                });

                ajaxRequest.done(function (xhr, textStatus) {
                    $("#response").attr('class', "alert alert-success");
                    $("#response").html("File uploaded successfully");
                });


            });
A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
  • Hi, how do you upload both image and data at the same time..? – gayan1991 Aug 10 '15 at 12:04
  • 1
    @gayan1991 You can build a request/form of type `multipart/form-data`. see https://stackoverflow.com/questions/4526273/what-does-enctype-multipart-form-data-mean also that might be helpful – A-Sharabiani Feb 23 '18 at 15:01
1

You can use either of the two plugins Jquery File Upload Plugins 1 or Jquery File Upload Plugins 2 and there's no errors on this script.

Hope it helps

Thanks, Rashid

Rashid
  • 9
  • 1
1

Ajax supports File upload using FormData Object, Also supports in all major browser except IE8/9 See below

https://developer.mozilla.org/en-US/docs/Web/API/FormData

lakhan_Ideavate
  • 375
  • 4
  • 14
0

Another option would be to base64 encode the file contents and send it as a string, decoding it at the back-end.

kmuenkel
  • 2,659
  • 1
  • 19
  • 20
-1

Simply use submit event on form to send the files and prevent default form action

$('#form').submit(function(e) { return false; });

and get the file on the server side via

$_FILES['inputName'];
Kirill
  • 19
  • 5