jquery – How to pass an empty array through ajax in php?

Question:

Create this array which is for storing addresses:

var arreglo_direcciones = [];

This arrangement, as I already mentioned, is to store addresses in another function that I have developed and it works perfectly, but when programming the main function of my form I realized that I had to validate that the addresses are required and that is where the problem comes. , when I pass the empty arreglo_direcciones array through ajax it does not pass next to the controller but if this array contains elements stored there it is passed to the controller and I can do any treatment to this array. the declaration of my main ajax function is the following:

$('#guardar-formulario').click(function(e){

    e.preventDefault();    

    $.ajax({
        type:'POST',
        url:'{{ route('regMiembros.store') }}',
        data:{ arreglo_direcciones: arreglo_direcciones },

        success:function(data){

            if($.isEmptyObject(data.errors)){

                $.smkAlert({
                    text: data.success,
                    type:'success'
                });

                limpiarErrores();   


            } else {

                limpiarErrores();

                $.each(data.errors, function (index, value) {
                    $('#_'+index).text(value);
                });

                $.smkAlert({
                    text: "Existen errores de validacion, por favor revise ",
                    type:'danger'
                });
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alerta(jqXHR.responseText);
        }
    });

});

Answer:

Try modifying the data sent in your ajax like this:

data:{ arreglo_direcciones: arreglo_direcciones.length ? arreglo_direcciones : null },

And in the validator or in the validation rules of your controller verify that the value is required, it should work.

Check this POST post in the answer they explain well why jquery does not pass the empty array.

Scroll to Top