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

uicabpatweyler's avatar

Get field: object error of jqXHR of ajax Jquery

I'm making a POST request using $.ajax({}) with Jquery. I purposely send missing fields to get server-side validation messages. The errors are these receiving in the following way in the object jqXHR.


error: function(jqXHR,textStatus,errorThrown){

    console.log(jqXHR.responseText);
        console.log(jqXHR.responseJSON);

}


The errors are shown as follows:


jqXHR.responseText

{"message":"The given data was invalid.","errors":{"recibo_de":["Recibo de: Requerido"],"id_proveedor":["Proveedor: Requerido"],"fecha_inicio":["Fecha inicial: Requerido"],"fecha_fin":["Fecha final: Requerido"]}}

jqXHR.responseJSON

{message: "The given data was invalid.", errors: {…}}

errors:

fecha_fin    : ["Fecha final: Requerido"]
fecha_inicio : ["Fecha inicial: Requerido"]
id_proveedor : ["Proveedor: Requerido"]
recibo_de    : ["Recibo de: Requerido"]
message      : "The given data was invalid."

With jqXHR.responseJSON.message I get the message "The given data was invalid.", Now, how can I get the fields one by one "recibo_de","id_proveedor","fecha_inicio","fecha_fin" along with your error messages?

0 likes
2 replies
Cronix's avatar
Cronix
Best Answer
Level 67
error: function(jqXHR, textStatus, errorThrown){
    var response = jqXHR.responseJSON;

    $.each(response.errors, function (fieldName, errorBag) {
        //output the fieldname for this error
        console.log(fieldName);

        // output each error message for this field
        $.each(errorBag, function(i, message) {
            console.log(message);
        });
    });
}
1 like

Please or to participate in this conversation.