Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Sunday, October 27, 2013

File Upload with jQuery and Ajax

The requirement is simple. I should be able to upload files to the server with jQuery and ajax. Lets get started.
<html>
   <form>
     File Description:<input type="text" id="desc" />
     Choose File:<input type="file" id="chosenFile" />
     <input type="button" id="submitFile" value="submitTheFile" />
   </form>
</html>
Now, the real jQuery stuff
<script type="text/javascript">
    jQuery.noConflict();
    jQuery(document).ready(function() {
        jQuery("#submitFile").click(function() {
            jQuery.ajax({
                url: "[url to be submitted to]",
                type: "POST",
                contentType: false,
                processData: false,
                data: function() {
                    var data = new FormData();
                    data.append("fileDescription", jQuery("#desc").val());
                    data.append("chosenFile", jQuery("#chosenFile").get(0).files[0]);
                    return data;
                    // Or simply return new FormData(jQuery("form")[0]);
                }(),
                error: function(_, textStatus, errorThrown) {
                    alert("Error");
                    console.log(textStatus, errorThrown);
                },
                success: function(response, textStatus) {
                    alert("Success");
                    console.log(response, textStatus);
                }
            });
        });
    });
<script>
Important things to be noted here are
contentType: false,
                processData: false,

contentType will be determined automatically, so we don't have to set that explicitly and processData has to be false, otherwise the data will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". Next important thing is

data: function() {
                    var data = new FormData();
                    data.append("fileDescription", jQuery("#desc").val());
                    data.append("chosenFile", jQuery("#chosenFile").get(0).files[0]);
                    return data;
                    // Or simply return new FormData(jQuery("form")[0]);
                }(),
You can read about FormData here. We basically set the values being submitted. The first parameter is the key and the second parameter is the actual value to be passed. We can get the value of any form field with
jQuery("#desc").val()
expect the files. If we use the same for files, we ll get just the file name instead of the file contents. So, we have to do something like
jQuery("#chosenFile").get(0).files[0]
If we dont want to set individual values and want to pass all the fields in the form, we can simply do
data: new FormData(jQuery("form")[0])
Thats it. Enjoy Ajaxified file upload :)
References:

Thursday, April 4, 2013

select2 JQuery dynamic JSON data with tags


          jQuery.noConflict();
          function formatListOptionSelection (Option, Container)
          {
             return Option;
          }
          function formatListOption (Option, Container, Query)
          {
             return "<div id='" + Option + "'>" + Option + "</div>";
          }
          jQuery(document).ready(function() {
             jQuery("#Data").select2 ({
                multiple: true,
                minimumInputLength: 5,
                maximumSelectionSize: 3,
                id: function (e) {return e;},
                ajax: {
                   url: 'fetch.json',
                   // json will be used if there is no Same Origin Policy violation, otherwise JSONP shall be used
                   dataType: 'json',
                   data: function (term, page) {
                      return {
                         searchkey: term,
                         field: 'Data'
                      };
                   },

                   // This method will be used when the data is returned from the server
                   results: function (data, page) {
                      return {results: data.Datas};
                   },
                },

                // This method will be used when you fetch result from server and add it to the element
                formatResult: formatListOption,

                // This method will be used when you select one of the options
                formatSelection: formatListOptionSelection,

                // This method will be used when you set the value attribute of the element
                initSelection: function(element, callback) {
                   var Datas = jQuery(element).val();
                   Data = []
                   jQuery(Datas.split(",")).each(function () {
                      if (this != "") Data.push (this);
                   });
                   callback (Data);
                },
             });
          });


         <input class="span12" id="Data" name="Data" type="hidden" value="<Value from POST back>" />