steve
steve

Reputation: 917

AJAX not getting response because of page refresh

I am implementing a feature which allows a user to upload a file which is processed server-side with some information returned as a JsonResult. This worked fine with another AJAX request where I sent only strings. It seems like because FormData is being sent it causes a page refresh, which for me means I never reach the response part of my code. I would appreciate it a lot if someone dug me out of this hole, thanks!

MyPage.cshtml

<input id="readFromFile" type="file"/>
<button class="btn btn-primary" type="submit" onclick="ResultsFromFile()">Get Results</button>
<script>
function ResultsFromFile() {
        var temp = $("#readFromFile")[0].files;
        if (temp.length > 0) {
            if (window.FormData !== undefined) {
                var data = new FormData();
                for (var x = 0; x < temp.length; x++) {
                    data.append("file" + x, temp[x]);
                }
                $.ajax({
                    type: "POST",
                    url: 'AlexaIndex?handler=GetResultsFromFile',
                    headers: { "XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val() },
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (response) {
                        console.log('result is ' + response);
                        var jsonObj = JSON.parse(response);
                        PopulateTable(jsonObj);
                    }
                });
            }
        }
</script>

MyPage.cshtml.cs

public JsonResult OnPostGetResultsFromFile()
{
    foreach (var file in Request.Form.Files)
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", file.FileName);
        using (var stream = new FileStream(path, FileMode.Create))
        {
            file.CopyTo(stream);
        }
        var urlList = ReadFileOfUrls(path);
        ModelState.Clear();
        var results = _alexaExtractorService.GetAwisResults(urlList);
        var json = JsonConvert.SerializeObject(results);
        return new JsonResult(json);
    }
    return new JsonResult("FINITO MINITO");
}

Upvotes: 0

Views: 50

Answers (2)

CoOl
CoOl

Reputation: 2797

The reason it's happening is because your button is wrapped in a form element, and all button elements with type="submit" will post the form to the server. Prevent the submit button from actually submitting by preventing that default action with e.preventDefault();

<input id="readFromFile" type="file"/>
<button class="btn btn-primary" type="submit" onclick="ResultsFromFile(event)">Get Results</button>
<script>
function ResultsFromFile(e) {
        e.preventDefault();
        var temp = $("#readFromFile")[0].files;
        if (temp.length > 0) {
            if (window.FormData !== undefined) {
                var data = new FormData();
                for (var x = 0; x < temp.length; x++) {
                    data.append("file" + x, temp[x]);
                }
                $.ajax({
                    type: "POST",
                    url: 'AlexaIndex?handler=GetResultsFromFile',
                    headers: { "XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val() },
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (response) {
                        console.log('result is ' + response);
                        var jsonObj = JSON.parse(response);
                        PopulateTable(jsonObj);
                    }
                });
            }
        }
</script>

Upvotes: 3

Umair Anwaar
Umair Anwaar

Reputation: 1138

Change the button type to type="button" instead of type="submit".

<button class="btn btn-primary" type="button" onclick="ResultsFromFile()">Get Results</button>

Upvotes: 2

Related Questions