Я хочу загрузить изображение, используя модал. Я знаю, как это сделать с помощью HTML-формы, но я не уверен, как использовать ajax-запрос для отправки данных в контроллер. Можно ли использовать контроллер, который у меня сейчас? Заранее спасибо!
Контроллер:
public function postCreatePost(Request $request)
{
...
$post->longitude = $request['longitude'];
if($request->user()->posts()->save($post))
{
$message = 'Post Successful';
};
$file = $request->file('image');
$filename = $post->id.'.jpg';
if($file)
{
Storage::disk('local')->put($filename, File::get($file));
}
return redirect()->route('dashboard')->with(['message' => $message]);
}
запрос ajax, который у меня есть:
$('#modal-save').on('click',function(){
//create ajax request
$.ajax({
method: 'POST',
url: urlEdit, //url route is defined in the dashboard html script
//pass the post content and id to body and postId which will be used in the Post controller edit method
//need the token to avoid error
data: {body: $('#post-content').val(), postId: postId, _token: token}
})
.done(function (msg){
//console.log(msg['message']);
//console.log(JSON.stringify(msg));
$(postBodyElement).text(msg['new_content']); //update the post w/o refreshing the page
$('#edit-post').modal('hide'); //hide the modal
})
});
Модал:
<div class="modal" tabindex="-1" role="dialog" id="edit-post">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Post</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form enctype="multipart/form-data">
<div class="form-group">
<label for="post-content">Edit Post</label>
<textarea class="form-control" name="post-content" id="post-content" rows="5"></textarea>
{{-- copy meta data using jquery?--}}
{{-- add a separate image form here--}}
<label for="image">Image (jpg only)</label>
<input type="file" name="image" class="form-control" id="image">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="modal-save">Save changes</button>
</div>
</div>
</div>
</div>