Should you check ajax return data or allow javascript to throw an error when data is empty?

Therefore, when you process, for example, success data in jquery, you should check if the return data has such necessary data:

success: function (data) {
    if (data.new_rank !== undefined) {
        $('._user_rank').html(data.new_rank);
    }
}

Or may he fail when he is not?

success: function (data) {
    $('._user_rank').html(data.new_rank);
}

in the previous example, you can check if something has changed and there should be fixt due to an error.

Which approach is best?

+4
source share
3 answers

You better check it out for other code that you might have in a full or different event. If you have not done so, they will not work after an error. You can also check this:

success: function (data) {
    if (data.new_rank) {
        $('._user_rank').html(data.new_rank);
    }
}
+2
source

jQuery ajax requests provide you with a way to handle request errors.

$.ajax(url, {
      success: function(data) {
          // success
      },
      error: function() {
         // error
      }
   });

, , javascript .

+2

One solution that I would say follows a strict data type in $ .ajax like dataType: json. Use a successful and error handler. And if the returned data is something other than the json type, it will be processed through an error handler.

$.ajax(url, {
      dataType: 'json'
      success: function(data) {
          // success
      },
      error: function() {
         // error
      }
   });
0
source

Source: https://habr.com/ru/post/1598877/


All Articles