Gabotronix's avatar

AJAX file upload failing validation?

Hi, so I created a form where I send some text along with an uploaded file (doc, docx files in this case). I get the following error message in console plus 422 status, unproccesable :

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

I think this is due to a validation fail maybe (the message could be much less vague...), what could I be doing wrong:

My form:

<form class="form_mainconteiner" style=" " enctype="multipart/form-data" method="POST" action="/contactar-mail-avanzado">
    <span class="form_label_text" style=" ">Nombre completo:</span>
    <input class="form_input" type="text" name="name" placeholder="" style="" required>
    <span class="form_label_text" style="">Correo electronico:</span>
    <input class="form_input" type="email" name="email" placeholder="" style="" required>
    <span class="form_label_text" style="">Mensaje:</span>
    <textarea class="form_textarea" name="message" style="" required></textarea>
    <span class="form_label_text" style="">Curriculum Vitae o similar:</span>
    <input class="form_input_file" type="file" name="file" placeholder="" style="" required>
    <button class="form_button sendAdvancedMail" type="button" style="">ENVIAR</button>
</form>```

This is my ajax call:

```php
$(".sendAdvancedMail").click(function(){
        var form = $(this).closest('form');
        console.log('button clicked');
        
        
        $.ajaxSetup({
            
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')}
        
        });
        
        $.ajax({
            
            async: true,
            url: '/contactar-mail-avanzado',
            type: 'POST',
            data: 
            {   
            'message_name': $("input[name='name']").val(),
            'message_email': $("input[name='email']").val(),
            'message_body': $("textarea[name='message']").val(),            
            'message_file': $("input[name='file']").val()
            },
            dataType: 'JSON',
            
            success: function (data) { 
                $('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                form.trigger("reset");
                console.log(data.success, data.errors);
            },
            
            error: function (data){
                var errors = data.responseJSON;
                console.log(errors);
                
                $.each(errors , function(){
                    $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                }); 
            }

        }); 
 
    });

This is my form request:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ContactFileMail extends FormRequest
{
    
    public function authorize()
    {
        return true;
    }

    
    public function rules()
    {
        return [
            
            'message_name' => 'required|string|min:3',
            
            'message_email' => 'required|email',
            
            'message_body' => 'required|string|min:5',
            
            'message_file' => 'required|size:5000|mimes:doc,pdf,docx,zip'
        ];
    }
}

And my controller method:

public function contactarArchivo(ContactFileMail $request)
    {
        
        $sender_mail = $request->email;;
        
        $destination_mail = config('globals.client_mail');
        
        $name = $request->message_name;
        
        $email = $request->message_email;
        
        $body = $request->message_body;
        
        $file = $request->message_file;
        
        $subject = "Solicitud de contacto de $name";
        
        $restaurant = config('globals.web_name');
        
        
        
        
        
        
        Mail::to($destination_mail)->send(new AdvContactMail($name, $email, $body, $file, $subject, $restaurant, $sender_mail));
        
        
        return response()->json(['success'=>'Mensaje enviado']);
    }
0 likes
2 replies
jcmargentina's avatar
Level 8

whats is the list of errors you get?

Also, as far as I know, you CANNOT upload a file by AJAX, unless you do something extra.

Mostly you need to use FormData.

Please read these links and you will get a better understanding of what I am talking about.

(Algunos en español para vos)

https://desarrolloweb.com/articulos/upload-archivos-ajax-jquery.html

https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

http://blog.teamtreehouse.com/uploading-files-ajax

https://stackoverflow.com/questions/4006520/using-html5-file-uploads-with-ajax-and-jquery

PD: This is expected, imagine if any website could just have a malicious javascript file, and could automatically upload an image from your computer??? Seria una mierda a? JAJA.

SALUDOS, marca mi respuesta como correcta de paso sumo puntos

_Artak_'s avatar

use FormData():

var formData = new FormData();

// NOTE. if file -  formData.append('message_file', $("input[name='file']").files[0])
//              formData.append('email', $("input[name='email']").val())
// . . .

$.ajax({
// . . .
data: formData
// . . .
})


1 like

Please or to participate in this conversation.