0

I am trying to submit a file via xmlHttpRequest - Ajax as per an example. The problem is when I click on the input button, the form is refreshing and trying to post it to the Action Method that renders this page. On submit button click I would like to post to an action method on the controller- fileUploadUrl which is a HTTP Post return JSON. It seems that my document.getElement form submit function is not firing at all and it is posting to this which is obviously not correct. /ErrorCode/Step1?id=form&enctype=multipart%2Fform-data.

I am trying to follow this example post a via ajax

@model Models.ErrorCodesStepsViewModel
@{
    ViewBag.Title = "Error Codes";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="@Url.Content("~/Content/css/Site.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/css/chosen.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/css/jquery.stepy.css")" rel="Stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery.stepy.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/chosen.jquery.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.MultiFile.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.fancytree.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.fancytree.filter.js")" type="text/javascript"></script>
<link href="@Url.Content("~/Content/themes/skin-xp/ui.fancytree.css")" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    var errorsSystemList = '@Url.Action("FindErrorSubsystem", "ErrorCode")';
    var instrumentSelectionUrl = '@Url.Action("Step2", "ErrorCode")';
    var fileUploadURL = '@Url.Action("Upload", "ErrorCode")';

    $(function () {
        $('form').stepy({
            backLabel: '<<',
            nextLabel: '>>',
            finishButton: false,
            next: function (index) {
                var v = $("#InsIdLst").chosen().val();
                if (v == null && index == 2) {
                    alert("Please select an Instrument");
                    return false;
                }
                else {
                    var overlay = $('<div></div>').prependTo('body').attr('id', 'overlay');
                    $.ajax({
                        type: 'GET',
                        url: instrumentSelectionUrl,
                        cache: false,
                        datatype: "html",
                        data: $("form").serialize(),
                        success: function (result) {
                            $("#errorCodes").html(result);
                            overlay.remove();
                        }
                    });
                }
                if (index == 3) {
                }
            }
        });
    });

}

<script type="text/javascript">



    $(document).ready(function () {
        $("#InsIdLst").chosen({ max_selected_options: 1 });

        $("#errorCodes").fancytree({

            icons: false
        });

        var errorTree;
        errorTree = $("#errorCodes").fancytree("getTree");

        var myform = document.getElementById("#form");


        $(myform).onsubmit = function () {
            alert("x");
            var formdata = new FormData(); //FormData object
            var fileInput = document.getElementById('fileInput');
            //Iterating through each files selected in fileInput
            for (i = 0; i < fileInput.files.length; i++) {
                //Appending each file to FormData object
                formdata.append(fileInput.files[i].name, fileInput.files[i]);
            }
            //Creating an XMLHttpRequest and sending
            var xhr = new XMLHttpRequest();
            xhr.open('POST', fileUploadURL);
            xhr.send(formdata);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    alert(xhr.responseText);
                }
            }
            return false;
        }

    });

</script>



  @using (Html.BeginForm(new { id = "form", enctype = "multipart/form-data" }))
{
    <fieldset title="Select">
        <legend>instrument</legend>
        <div class="bodyContent">
            <span class="rightContent">
                @Html.ListBoxFor(model => model.SelectedInstrumentTypeID, Model.InstrumentTypeIds, new { id = "InsIdLst", name = "listbox", @class = "chosen-select", multiple = "multiple", data_placeholder = "Click here to Select An Instrument...", style = "width:90%;", tabindex = "5" })
            </span>
        </div>
    </fieldset>
    <fieldset title="View">
        <legend>Problem codes</legend>
        <div id="errorCodes">
        </div>
    </fieldset>
    <fieldset title="Upload">
        <legend>upload file</legend>
        <div class="bodyContent">
            <input id="fileInput" type="file" />
            <input type="submit" value="Upload file" />
        </div>
    </fieldset>
    <fieldset title="Review">
        <legend>description two</legend>
        <!-- inputs -->
    </fieldset>
    <fieldset title="Save">
        <legend>description two</legend>
        <!-- inputs -->
    </fieldset>
}
Community
  • 1
  • 1
tam tam
  • 1,870
  • 2
  • 21
  • 46
  • Do you have an element with the `id="form"`? If not your submit handler won't ever trigger and the form submission will occur as default behavior. – Jasen Aug 22 '15 at 02:34
  • Also, if you're already using jQuery for one AJAX request why not keep things consistent and do the same for your POST? – Jasen Aug 22 '15 at 02:35
  • @Jasen I did correct the form and added the id – tam tam Aug 22 '15 at 03:01
  • @Jasen because I believe you cannot upload files via ajax, I know its still through XML Http Request object but I believe you have to use javascript, – tam tam Aug 22 '15 at 03:16

1 Answers1

0

Since you're using jQuery, you shouldn't bind to the native onsubmit event, but to the submit event:

var $myForm = $("#myForm").on("submit", function(event) {
   return $.ajax({
       // ...
   }).then(function() { return false; });
});

Note the return false in the code; if you don't return false, the form will submit normally.

Alternatively, you can use the shorthand submit jQuery method. See the documentation for more info.

user1429980
  • 6,872
  • 2
  • 43
  • 53
  • where should I add the above, in document.ready function and I am confused with the return ajax. I need to use the logic in my original onSbumit function – tam tam Aug 22 '15 at 03:04