Я пытаюсь создать раздел редактирования для моей страницы продуктов,
Я использую Ajax, чтобы я мог редактировать разделы, не переходя на другую страницу.
Я успешно могу загрузить текстовые значения во второй форме, но проблема, с которой я сталкиваюсь, заключается в том, что я не могу добавить изображение в эту существующую форму.
Вместо этого я использовал обычный метод для его обновления.
Я думаю, что это неэффективный способ, может кто-нибудь предложить мне лучшую альтернативу для этого
Вот мой код,
Blade
Обе формы находятся на одной странице
<form action="{{route('degreeguides.update', $degreesembooks->id)}} " method="POST" enctype=multipart/form-data> @csrf
<div class="form-group">
<input type='file' id="coverImgInp" name="cover_image" />
<button type="button" id="img-edit" class="btn" data-toggle="modal" data-target="#myModal2">Edit</button>
<img id="cover_image" class="crop img-fluid" height="50" src="#" alt="Image" />
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="hidden" name="title" value="{{$degreesembooks->title}} ">
<input type="hidden" name="description" value="{{$degreesembooks->description}} ">
<input type="hidden" name="amount" value="{{$degreesembooks->amount}} ">
</div>
<button type="submit" name="img-upload" class="btn">Upload</button>
</form>
В приведенной выше форме я собираю значения и возвращаю их как есть.Но я не уверен, насколько эффективно это будет. Совет очень важен
Для формы ниже, я использую Ajax для обновления значений, и она отлично работает!
<form action="" method="POST">
@csrf
<div class="card-description">
<h3 contenteditable="true" class="title"> {{$degreesembooks->title}} </h3>
<p>Book Code : <span contenteditable="true" class="book_code">{{$degreesembooks->book_code}} </span> </p>
<h1>INR <span contenteditable="true" class="amount">{{$degreesembooks->amount}}</span></h1>
<p contenteditable="true" class="description">{{$degreesembooks->description}} </p>
<h4>Available Stock : <span contenteditable="true" class="quantity">{{$degreesembooks->quantity}} </span> </h4>
<br>
<button type="submit" id="ajaxSubmit"> Update</button> <button type="button" id="#form-reset">
Reset
</button>
{{-- <div id="success_message"></div>s --}}
</div>
</form>
Ajax
$('#ajaxSubmit').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var id = $('#product_id').val();
$.ajax({
url: "{{ url('degreeguidesem/')}}/" + id,
method: 'post',
data: {
id: $('#product_id').val(),
title: $('.title').text(),
amount: $('.amount').text(),
description: $('.description').text(),
quantity : $('.quantity').text(),
},
success: function(data){
bootbox.alert("The information has been succesfully updated.!", function() {
});
},
error: function (err) {
if (err.status == 422) { // when status code is 422, it's a validation issue
console.log(err.responseJSON);
bootbox.alert("The information has been succesfully updated.!", function() {
})
// loop through the errors object and show it to the user
console.warn(err.responseJSON.errors.title[0]);
}
}
});
});
Мои маршруты
Route::post('degreeguidesem/{id}','BooksController@update')->name('degreeguides.update');
Мой контроллер:
public function update(Request $request, $id)
{
$degreebooks = Books::where('id', '=', $request->id)->first();
$degreebooks->title = $request->title;
$degreebooks->amount = $request->amount;
$degreebooks->description = $request->description;
$degreebooks->id = $request->id;
if (Input::hasFile('cover_image')) {
if ($request->w) {
$image = $request->file('cover_image');
$file_replace = $image->getClientOriginalName();
$filename = 'ascdf-' . $file_replace;
$path = public_path('images/bookcover/' . $filename);
$w = intval($request->input('w'));
$h = intval($request->input('h'));
$x = intval($request->input('x'));
$y = intval($request->input('y'));
Image::make($image->getRealPath())
->crop($w, $h, $x, $y)
->resize(800, 600)
->save($path);
$degreebooks->cover_image = $filename;
} else {
$image = $request->file('cover_image');
$file_replace = $image->getClientOriginalName();
$filename = date('Y-m-d-H:i:s') . '-' . $file_replace;
$path = public_path('images/bookcover/' . $filename);
Image::make($image->getRealPath())
->resize(800, 600)
->save($path);
$degreebooks->cover_image = $filename;
}
}
$degreebooks->save();
return response()->json([
'message' => "Welcome Error"
]);
}
Теперь и текстовые поля, и поля изображений работают независимо, как их объединить?Любая помощь приветствуется.