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
JavaScript
x
9
1
@foreach ($courses as $course)
2
<tr>
3
<td>{{ Form::select('year', $years, ['class' => 'form-control'], [ 'placeholder' => $course->academicYear]) }}</td>
4
<td>{{ Form::select('subject', $subjects, ['class' => 'form-control'], [ 'placeholder' => $course->subject]) }}</td>
5
<td>
6
<a href="" id="saveCourse" class="btn btn-success pull-left">Save</a>
7
<input type="hidden" id="idCourse" value="{{ $course->id }}">
8
( )
9
JQUERY + AJAX
JavaScript
1
36
36
1
$('#saveCourse').click(function(e){
2
e.preventDefault();
3
var id = $('#idCourse').val();
4
5
// Ignore this logic
6
var values = {year: "", subject:"", id: id};
7
var parameters = ['year', 'subject'];
8
var i = 0;
9
$('td > select option:selected').each(function() {
10
values[parameters[i]] = $(this).text();
11
i++;
12
});
13
14
// Ajax request
15
$.ajax({
16
type: 'patch',
17
18
// Appending the course id here not working,
19
// but if i put anything else like /blabla/ + id ajax doesn't ignore it...
20
21
url: '/courses/' + id,
22
headers: {'X-CSRF-Token': csrf_token},
23
dataType: 'json',
24
data: values,
25
26
success: function (response) {
27
console.log("SUCCESS: " + response);
28
},
29
error: function (reject) {
30
if( reject.status === 422 ) {
31
$("#error").text("Los datos dados no cumplen el formato requerido.");
32
}
33
}
34
});
35
});
36
WEB.PHP
JavaScript
1
5
1
/* -----COURSE_ROUTES------ */
2
Route::resource('courses', 'CourseController')->except([
3
'create', 'edit'
4
]);
5
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!
JavaScript
1
2
1
if(request()->ajax()) { }
2