I try to make an ajax request through JQuery triggering an onClick event, but when it sends the AJAX request I receive:
PATCH http://localhost:8000/courses 405 (Method Not Allowed) (Current page) Because it doesn’t get the URL with the id
HTML
@foreach ($courses as $course) <tr> <td>{{ Form::select('year', $years, ['class' => 'form-control'], [ 'placeholder' => $course->academicYear]) }}</td> <td>{{ Form::select('subject', $subjects, ['class' => 'form-control'], [ 'placeholder' => $course->subject]) }}</td> <td> <a href="" id="saveCourse" class="btn btn-success pull-left">Save</a> <input type="hidden" id="idCourse" value="{{ $course->id }}"> (...)
JQUERY + AJAX
$('#saveCourse').click(function(e){ e.preventDefault(); var id = $('#idCourse').val(); // Ignore this logic var values = {year: "", subject:"", id: id}; var parameters = ['year', 'subject']; var i = 0; $('td > select option:selected').each(function() { values[parameters[i]] = $(this).text(); i++; }); // Ajax request $.ajax({ type: 'patch', // Appending the course id here not working, // but if i put anything else like /blabla/ + id ajax doesn't ignore it... url: '/courses/' + id, headers: {'X-CSRF-Token': csrf_token}, dataType: 'json', data: values, success: function (response) { console.log("SUCCESS: " + response); }, error: function (reject) { if( reject.status === 422 ) { $("#error").text("Los datos dados no cumplen el formato requerido."); } } }); });
WEB.PHP
/* -----COURSE_ROUTES------ */ Route::resource('courses', 'CourseController')->except([ 'create', 'edit' ]);
EDIT
If I use POST
instead of PATCH
in type
AJAX gets the id.
Found a GitHub issue with the same problem https://github.com/jquery/jquery/issues/3944
Advertisement
Answer
I forgot to put this condition at the start of the update method in the controller… Now it works!
if(request()->ajax()) { ... }