skip to Main Content

how do i approach this error given in array and i want the error to populate on my Bootstrap alert

Ajax code

 $.ajax({
            type: type,
            url: ajaxurl,
            data: formData,
            dataType: 'json',
            success: function (data) {
              
               if(data.status){
                SuccessMessage();
                setTimeout(function() {
                    location.reload();
                }, 300);
            }
        },
        error: function (data) {
         
            console.log('Error:', data.responseJSON.errors);
                
            }
        });
    });

json response

{name: Array(1), email: Array(1), password: Array(1)}
email: ["The email field is required."]
name: ["The name field is required."]
password: ["The password field is required."]

Bootstrap alert:

<div class="alert alert-danger" style="display:none"></div>

2

Answers


  1. Please try it:

     $.ajax({
        type: type,
        url: ajaxurl,
        data: formData,
        dataType: 'json',
        success: function (data) {
    
            if (data.status) {
                SuccessMessage();
                setTimeout(function () {
                    location.reload();
                }, 300);
            }
        },
        error: function (data) {
            const errors = Object.values(data.responseJSON.errors)
            if (errors.length === 0) {
              return
            }
    
            errors.forEach(item => {
              $('.alert-danger').append(`<h1>${item}<h1>`)
            })
    
            $('.alert-danger').show();
        }
    });
    

    With specific columns:

    error: function (data) {
            const errors = Object.keys(data.responseJSON.errors)
            
            if (errors.length === 0) {
                return
            }
    
            const errorKeys = Object.keys(errors)
            errorKeys.forEach(item => {
                const errorItems = errors[item];
                errorItems.forEach(error => {
                    $(`.invalid-feedback-${item}`).append(`<h1>${error}<h1>`)
                })
            })
    
            // Please test it. I'm not sure the below function works
            $('[class^=invalid-feedback-]').show()
        }
    
    Login or Signup to reply.
  2. <div class="alert alert-danger" role="alert">
      <h4 class="alert-heading">Validation failed!</h4>
      <p id="alert"></p>
    </div>
    
    error: function (data) {
    
    $('#alert').text(data.responseJSON.errors.join(", "))
    $('.alert').alert()
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search