0

Just want to alert a message when there are some unexpected errors(I changed 'controller/get_data' to 'controller/get_dat') but it does not alert anything. Could you please check what is wrong with my error handling function.

$.get('controller/get_data', function (data) {
        if (data.message !== undefined) {
            $( "#data_is_not_got").text(data.message);
        } else {

           //displaying posts               

        }
    }, "json").error(function(jqXHR, textStatus, errorThrown){
             alert("Something gone wrong. Please try again later.");
 });
EducateYourself
  • 971
  • 2
  • 13
  • 32

2 Answers2

2

.error is not what you expect it to be. Furthermore, it's deprecated. What you want is .fail()

.fail(function(){
     alert("Something gone wrong. Please try again later.");
});
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • thanks a lot for your help. I would like to understand if I cover all the unexpected errors with fail() ? and if error(function(jqXHR, textStatus, errorThrown){} should not be used anymore? – EducateYourself Sep 05 '14 at 15:41
  • @EducateYourself Correct. do not use `.error()` anymore. Furthermore, as `.fail` is a deferred handler, it will catch any failures associated with the $.get request, such as 500, 404, 403, etc. – Ohgodwhy Sep 05 '14 at 15:42
  • thanks! Sorry but I also would like to know if there is need to write something in the brackets? or just leave it empty like fail(). – EducateYourself Sep 05 '14 at 15:45
  • @EducateYourself There's no reason to put anything in the brackets. – Ohgodwhy Sep 05 '14 at 15:46
1

I believe you need to try .fail instead of .error.

$.get('controller/get_data', function (data) {
        if (data.message !== undefined) {
            $( "#data_is_not_got").text(data.message);
        } else {

           //displaying posts               

        }
    }, "json").fail(function() {
             alert("Something gone wrong. Please try again later.");
 });

Otherwise, you could use the more basic $.ajax.

$.ajax({
    url: 'controller/get_data',
    type: 'GET',
    success: function(data){ 
        // Do something with data
    },
    error: function(data) {
        alert('Something's gone wrong!');
    }
});
D'Arcy Rail-Ip
  • 11,505
  • 11
  • 42
  • 67