Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

trav1s's avatar

How to correctly display errors from AJAX?

Hello, guys! I want to display an error for each input individually. .Any advice or help would be greatly appreciated. What am I doing wrong?

            error: function (jqXHR, exception) {
                if (jqXHR.status === 0) {
                    alert('Not connect. Verify Network.');
                } else if (jqXHR.status == 404) {
                    alert('Requested page not found (404).');
                } else if (jqXHR.status == 500) {
                    alert('Internal Server Error (500).');
                } else if (exception === 'parsererror') {
                    alert('Requested JSON parse failed.');
                } else if (exception === 'timeout') {
                    alert('Time out error.');
                } else if (exception === 'abort') {
                    alert('Ajax request aborted.');
                } else {
                    $(".invalid-feedback").append(JSON.stringify(jqXHR.responseText));
                }
            },

What is the best way to display an error for each input individually?

Thank you for your attention

0 likes
5 replies
tisuchi's avatar

@trav1s I probably follow this way:

$.ajax({
    // your ajax code here
    success: function(response){
      // handle success here
      $(response.errors).each(function(key, value){
        $("input[name='"+key+"']").next(".invalid-feedback").text(value);
      });
    },
    error: function(response){
      // handle error here
    }
});
1 like
trav1s's avatar

@tisuchi but why your code are located in success? Don't quite understand to be honest

tisuchi's avatar

@trav1s Apology. I misplaced it. That's what I mean.

$.ajax({
    // your ajax code here
    success: function(response){
      // handle success here
    },
    error: function(response){
        // handle error here
        $(response.errors).each(function(key, value){
            $("input[name='"+key+"']").next(".invalid-feedback").text(value);
        });
    }
});
1 like

Please or to participate in this conversation.