G A
G A

Reputation: 591

Parsing a JSON response after a file upload with jquery

I have written a small script using jquery to upload a file to a server. The file is uploaded successfully and the done: event is called with no problems, but I am having issues to process the answer. This is my script:

    <input id="fileupload" type="file" name="carPicture" accept="image/*" multiple>
    <div id="progress">
        <div class="bar" style="width: 0%;"></div>
    </div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
    <script src="@routes.Assets.at("javascripts/vendor/jquery.ui.widget.js")" type="text/javascript"></script>
    <script src="@routes.Assets.at("javascripts/jquery.iframe-transport.js")" type="text/javascript"></script>
    <script src="@routes.Assets.at("javascripts/jquery.fileupload.js")" type="text/javascript"></script>
    <script>
        $(function () {
            'use strict';
            // Change this to the location of your server-side upload handler:
            var url = "uploadCarPicture";
            $('#fileupload').fileupload({
                url: url,
                dataType: 'json',
                done: function (e, data) {
                    $.each(data.result.files, function (index, file) {
                        $('<p/>').text(file.name).appendTo('#files');
                    });
                },
                fail: function (e, data) {
                    alert("File exists");
                    },
                progressall: function (e, data) {
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    $('#progress .bar').css(
                            'width',
                            progress + '%'
                    );
                }
            }).prop('disabled', !$.support.fileInput)
                    .parent().addClass($.support.fileInput ? undefined : 'disabled');
        });
    </script>

I am having two problems:

  1. the variable data seems to be empty since the loop below doesn't run even once.

            $.each(data.result.files, function (index, file) {
                $('<p/>').text(file.name).appendTo('#files');
            });
    
  2. The answer is a JSON document with the following format: {"e":0} where "e" is an error code. "e" could return many different values and I would like to be able to find out the real response and not always assume 0.

Any idea?

Upvotes: 1

Views: 18611

Answers (1)

G A
G A

Reputation: 591

I have solved it. I've made a small change in the java script like this:

done: function (e, data) {
      $.each(data.files, function (index, file) {
          $('<p/>').text(file.name);
        });
      },

And I have changed the json that the server was responding to this format:

{ files: [ { error: 0, name: "thumb2.jpg", } ] }

Upvotes: 9

Related Questions