I have some problems with my ajax call, I have a collection group and when I click on show link it should show me the collection's tasks.The problem is when I try to create new tasks for the current collection.I made 50% of the problem, because it creates the records in database, but something strange happen.
Form is already submitted even If I do not click the create button
After ajax call, it creates the records in database, but it does not append the newly created element, it shows me this:
Here is my ajax script:
$(document).ready(function() {
// store task
$('#create-task').click(function (event) {
event.preventDefault();
$.ajax({
type: 'post',
dataType: 'json',
data: $('#create-task-form').serialize(),
success: function (data) {
$('#create-task-form').trigger('reset');
$('#createTaskModal').modal('hide');
$('.collections').append('<li>' + data.name + '</li>');
}
});
});
});
I did not set the url, because when I do that it shows me something like this, and I do not know why.
Duplicate collection/collection/id
Routes:
// Collection routes
Route::prefix('collections')->middleware('auth')->group(function() {
Route::get('/', 'CollectionController@index')->name('collections.index');
Route::post('/', 'CollectionController@store')->name('collections.store');
Route::get('/{collection}', 'CollectionController@show')->name('collections.show');
Route::get('/{collection?}/edit', 'CollectionController@edit')->name('collections.edit');
Route::patch('/{collection?}', 'CollectionController@update')->name('collections.update');
Route::delete('/{collection?}', 'CollectionController@destroy')->name('collections.destroy');
Route::post('/{collection?}', 'CollectionController@storeTask')->name('tasks.store');
});
Controller
public function storeTask(Request $request)
{
$attributes = $request->validate([
'name' => 'required|min:3',
'description' => 'nullable|min:3',
'status' => 'required',
'due' => 'nullable|date'
]);
$attributes['collection_id'] = $request->collection;
$task = Task::create($attributes);
return Response::json($task);
}
PS: I can still create records, even the validation from back-end fails!