1

i'm trying to validate an image field in a Laravel form using AJAX but it allways seems to be empty. Even if i've already selected an file. How can i do it to check if the file input is empty or not with the ajax validation?

The form code:

{{ Form::open('files'=>'true') }}
    ...
    {{ Form::file('image') }}
    ...
{{ Form::close() }}

The AJAX call:

var form_data = $("#form").serialize();
$.ajax({
            dataType:"json",
            method:'post',
            url:'/ajax/validate?'+form_data,
            success:function(data){...}
});

The controller side:

...
$rules['image'] = 'required';
...
$validator = Validator::make(Input::all(),$rules);
if($validator->fails()){
    ...
}else{
    ...
}

1 Answer 1

1

I had same problem.

Mine was kinda fixed by replacing serialize() with FormData() . here is how it goes in jquery/ajax:

$("#form").submit(function(e){
        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            type : "post",
            url : '{{ URL::to('/post')}}',
            dataType : "json",
            data: new FormData(this),
            processData: false,
            contentType: false,
            success : function(response){
                if(response.success == true){
                    alert('done');
                }else{
                     $.each(response.errors,function(k,error){
                         alert(error);
                     }
                }
            }
        });
});

and in laravel validation you need to return response as jSon (I don't write complete code here):

if($validator->fails()){
    $errors = $validation->getMessageBag()->toArray();
    //Below Error also might work :
    //$errors = $validator->messages()->all();
    $result = ['success' => false , 'errors' => $errors];
}else{
     $result = ['success' => true, 'errors' => null];
}
return Response::json($result);

Note I'm still working on this . I'm pretty sure it detects images because when (in my case) image size is more than 2MB it does not upload it. it detects images if you use FormData() ...

I'm just not sure about the response.

Good Luck;

EDIT

To validate max file size, you should edit upload_max_filesize in your php.ini directly . otherwise Laravel might not be able to detect more than 2MB file size (I guess) because php itself stops it.

now my validation worked correctly.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to Alexandre Thebaldi , stackoverflow.com/questions/32279631/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.