Check if AJAX response data if is empty or null than don't show in output

6.2k Views Asked by At

This is ajax function, I want when data is null or undefined than output (#access element) show me empty "" ( or don't save any data in output when is null or not found )

  $(function(){

    $('#userId').on('keyup', function () {
      var value=$(this).val();
      $.ajax('/projectname/admin/getUserAccess/' + value,
        {
          dataType: 'JSON',
          success: function(data){

              var str = data.access.replaceAll(/\|/g, ',');
              var result = str.substring(1, str.length - 1);

              $("#access").val(result);

          }
        });
    });
  });
3

There are 3 best solutions below

1
On

I suggest adding a simple generic function to check emptiness/undefined as this will be handy for other parts of your project too. The Generic function goes like this:-

function isEmpty(value) {//Function to check if value is Empty or Null
              switch (typeof(value)) {
                case "string": return (value.length === 0);
                case "number":
                case "boolean": return false;
                case "undefined": return true;
                case "object": return !value ? true : false; // handling for null.
                default: return !value ? true : false
              }
            }

Thereafter update your success as follows:-

success: function(data){
     if(isEmpty(data)){
       $("#access").html(data); //Notice it is Html and not val as you want data displayed
     }else {
       window.alert('Nothing Returned');//If at all you want an Alert
       $("#access").html('');//Sets the $("#access") with nothing to display
     }

I hope this resolves the hurdle

0
On

thank you for all comment and answers i learn more things of other answer :) i added line $("#access").val("") and problem fixed.

      success: function(data){
          $("#access").val("");
          var str = data.access.replaceAll(/\|/g, ',');
          var result = str.substring(1, str.length - 1);

          $("#access").val(result);

      }
2
On

Just add a condition to check, if data is present or not as

If(data) {
    var str = data.access.replaceAll(/\|/g, ',');
    var result = str.substring(1, str.length - 1);

    $("#access").val(result);
}