jqueryajaxlaravelcallbackformvalidation.io

Formvalidation ajax cannot read property 'message' of undefined


I'm using formvalidation.io plugin and i'm trying to validate a field to be unique in database table. I have done the comparing, and i'm returning the result (unique or not) using ajax. I use 'callback validator' from formvalidation plugin (http://formvalidation.io/validators/callback). Here is my code:

callback: { //check documento no repetido
    message: 'Ya existe un estudiante con el mismo número de documento',
    callback: function (value, validator, $field) {
        var url = "documento-existe";
        $.ajax({
            type: "POST",
            url: url,
            data: $("#numero_documento").serialize(),
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(data)
            {
                console.log(data);
                return data;
            }
        });
    }
}

This code gives me an error ncaught TypeError: Cannot read property 'message' of undefinedin javascript console. Why can this error is caused?

I know there is a 'remote validator' from formvalidation plugin to do ajax-through validation (http://formvalidation.io/validators/remote/), but i'm using Laravel, and i have to send ajax headers (X-CSRF-TOKEN), and the 'remote validator' doesn't have the ability to send ajax headers.


Solution

  • Finally the 'remote' method accepts header. It was not specified in the documentation. My solution was:

    remote: {
        message: 'Ya existe un estudiante con el mismo número de documento',
        url: 'documento-existe',
        type: 'POST',
        data: function() {
            return {
                numero_documento: $("#numero_documento").val()
            };
        },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    }
    

    Anyway, I don't like this warning in console:

    Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.