0

I have a Web app (MVC 5), and when I move fast from index page to different page i get a javascript alert tell me : "The page at localhost:4332 says: " (its says nothing).

and when i press the OK button, evertything is back to normal its continue to the other page, i want to disable this alert from pop to the client.

I'm thinking its because i move to a different page too fast and the script cant run fully.

What i do in the script is initialize a drop down list with values i get from Ajax post request. (in order to save time from the load the page time, i load the page and than initialize the drop down list.

this is my code :

$(document).ready(function () {

    $.ajax({
                type: 'POST',
                url: '/Home/GetProfiles',

                success: function (data) {
                    $.each(data, function (key, value) {

                        $('#filterSelect').append($("<option></option>").attr("value", value).text(key));

                    });

                },
                error: function (ts) { alert(ts.responseText) }

            }); 

})

I do a couple things more but i don't want to complicate the code that i posted here, i think the problem is related to this lines of code.

I try to add "try" and "catch" with console.log of the exception but i didn't get nothing to the console, and the alert keep pops

Any idea why its happens ? and how can i fix it ?

Ron
  • 1,744
  • 6
  • 27
  • 53

2 Answers2

2

You're getting a message because navigating the page cancels any AJAX requests, so they'll error. You have an onerror callback that shows the responseText, and since it errored there's no text to show.

Andrea
  • 19,134
  • 4
  • 43
  • 65
0

@Andrea Faulds is correct. This is happening because the page content changes before the ajax call finishes. This can happen when you quickly navigate to another page, or reload the current page, before the ajax call finishes.

For appropriate fix, see this URL: handle ajax error when a user clicks refresh

To summarize, many people do something like this:

error: function (ts) {
    if (ts.readyState == 0 || ts.status == 0) return;
    alert(ts.responseText);
}

However, this can also suppress real errors. For example, if you begin the ajax request, and then disable your network connection, you may never see the alert message (because in these cases, readyState and status are also zero).

Another possible solution is for you to do something like this:

error: function (ts) {
    alert(ts.responseText || 'An asynchronous request was unable to complete.');
}

In this case, by using the || operator, your user will still see the alert when the page content changes before the ajax call finishes. However the alert will not be blank, because when it is, the other message will be shown.

Community
  • 1
  • 1
danludwig
  • 46,965
  • 25
  • 159
  • 237