DWQA QuestionsCategory: Laravelhow to submit form with file using ajax in laravel
kundan roy asked 5 years ago
  1. AJAX Code

<script type=”text/javascript”>
$(“form#user-form”).validate({
errorLabelContainer: ‘.error-loc’,
rules: {
blog_title: {
required: true
},
blog_description: {
required: true,
}
},
// Specify the validation error messages
messages: {
blog_title: {
required: ‘title is required’},
blog_description: {
required: ‘blog description is required’,
},
},
submitHandler: function(event) {
$(“form#user-form”).submit();
}
});

jQuery(‘form#user-form’).submit(function(event) {
event.preventDefault();
var formData = new FormData(jQuery(this)[0]);
var form_data = new FormData();
var file_data = $(‘input[name=”blog_image”]’).prop(‘files’)[0];
form_data.append(‘file’, file_data);
$(‘form.user-form’).find(‘input’).each(function( key, value ) {
// console.log($(this).attr(‘name’),$(this).val());
form_data.append($(this).attr(‘name’), $(this).val());
});
jQuery.ajax({
url: ‘{{url(“admin/blog/ajax”)}}’,
type: ‘POST’,
cache: false,
processData: false,
contentType : false,
data: form_data,
success: function (data) {
console.log(data);
}
});
return false;
});
</script>

Laravel Code :
public function ajax(Request $request, Blogs $blog){

if ($request->file(‘file’)) {

$photo = $request->file(‘file’);
$destinationPath = storage_path(‘blog’);
$photo->move($destinationPath, time().$photo->getClientOriginalName());
$blog_image = time().$photo->getClientOriginalName();
$blog->blog_image = $blog_image;
}
exit();
}