F
F
fryette2014-11-22 06:08:00
JavaScript
fryette, 2014-11-22 06:08:00

Why doesn't ajax and my script work together?

@model Slika.WebUI.Models.ImagesListViewModel
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="/Content/FIleUpload.css" type="text/css">
    <meta name="viewport" content="width=device-width" />
    <script src="/Scripts/MyScript/fileUpload.js"></script>
    <script type="text/javascript" src="/Scripts/MyScript/Gallary.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('form').submit(function () {
                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: $(this).serialize(),
                    success: function (result) {
                        $('#images').html(result);
                    }
                });
                return false;
            });
        });
    </script>
</head>
<body>
    <div id="myForm">
        @using (Html.BeginForm("SaveImage", "Image", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            @Html.Hidden("AlbumID", Model.AlbumID)
            @Html.Hidden("page", Model.PagingInfo.CurrentPage)
            <div class="file_upload">
                <button type="button">Выбрать</button>
                <div ng-app="myApp" ng-controller="myController">Select</div>
                <input type="file" accept="image/*" multiple="multiple" name="images">
            </div>
            <br />
        }
    </div>
    <div id="images">
        @{
            Html.RenderPartial("ImageSummary", Model);
        }
    </div>
    <div class="pager">
        @Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new { page = x, Model.AlbumID }))
    </div>
</body>
</html>


And such a script designed to download files
$(function () {
    var wrapper = $(".file_upload"),
        inp = wrapper.find("input"),
        btn = wrapper.find("button"),
        lbl = wrapper.find("div");

    // Crutches for the :focus style:
    btn.focus(function () {
        wrapper.addClass("focus");
    }).blur(function () {
        wrapper.removeClass("focus");
    });

    // Yep, it works!
    btn.add(lbl).click(function () {
        inp.click();
    });

    var fileApi = (window.File && window.FileReader && window.FileList && window.Blob) ? true : false;

    inp.change(function () {

        var fileName;
        if (fileApi && inp[0].files[0])
            fileName = inp[0].files[0].name;
        else
            fileName = inp.val().replace("C:\\fakepath\\", '');
        if (!fileName.length)
            return;

        if (lbl.is(":visible")) {
            lbl.text(fileName);
            btn.text("Выбрать");
        } else
            btn.text(fileName);
    }).change();
    $('body').on('change', 'input[type=file]', function () { $('form').submit(); });
});
$(window).resize(function () {
    $(".file_upload input").triggerHandler("change");
});


The problem is that null comes to the controller instead of images
and the page is reloaded by ajax, if you remove the code with ajax, images are loaded perfectly. Maybe someone has already encountered this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mr_Smitt, 2014-11-22
@fryette

As far as I know $.ajax can't send files
Try like this:

$(document).on('submit', '#user_files', function () {
    var self = this;
    var files = document.querySelector('input[type="file"]').files;
    var formData = new FormData();

    for (var i = 0, file; file = files[i]; ++i) {
      formData.append(file.name, file);
    }

    var xhr = new XMLHttpRequest();
    xhr.open('POST', $(self).attr("action"), true);
    xhr.upload.onprogress = function (e) {
      if (e.lengthComputable) {
        if (((e.loaded / e.total) * 100) >= 100) {
          alert("Загрузил!");
        }
      }
    };
    xhr.send(formData);
    return false;
  });

+ option with possible progressbar
$(document).on('submit', '#user_files', function () {
    var self = this;
    var files = document.querySelector('input[type="file"]').files;
    var progress = $(".progress .bar");
    var formData = new FormData();

    for (var i = 0, file; file = files[i]; ++i) {
      formData.append(file.name, file);
    }

    var xhr = new XMLHttpRequest();
    xhr.open('POST', $(self).attr("action"), true);

    xhr.upload.onprogress = function (e) {
      if (e.lengthComputable) {
        progress.css({"width": ((e.loaded / e.total) * 100) + "%"});
        if (((e.loaded / e.total) * 100) >= 100) {
          alert("Загрузил!");
        }
      }
    };

    xhr.send(formData);
    return false;
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question