show some controller codes please
Controller don't return view after AJAX post
Hi guys,
I'm struggling with a little problem for a few days and maybe you could enlight me up.
Imagine that I have a form with two inputs to let the user find a book (by name and category). And on submit, he´s redirected to a page listing the results.
I've done this with a GET method, but as a GET my url turns in something like: http://localhost:8000/en/search?search_book=NAME&type_select=CATEGORY
route:
Route::get('/search', 'BookController@findBooks')->name('search');
Now I'm looking for something cleaner like http://localhost:8000/en/search/NAME/CATEGORY
For this, I've changed my route to
Route::post('/search/{name}/{category}', 'BookController@findBooks')->name('search');
Added two parameter on my controller. (This controller simply run a few queries and return a view with the results.)
And changed my form submit mode. Now I'm submit the request by AJAX call.
<script type="text/javascript">
var frm = $('#form_sub');
frm.submit(function (e) {
e.preventDefault();
var name = $('#bk_name').val();
var category = $('#bk_category').val();
var url = '{{ route("search", [":name", ":category"] ) }}';
url = url.replace(':name', name);
url = url.replace(':category', category);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});
$.ajax({
type: frm.attr('method'),
url: url,
data: frm.serialize(),
dataType: 'html',
success: function (data) {
$('body').html(data);
},
error: function (data) {
console.log('An error occurred.');
},
});
});
</script>
And now there's the problem. On submit I wont see any change on my browser. But I could see on Network tab (on preview) my page with the results.
I'm trying to understand, why my controller don't return the view as it should.
Any ideas? Or I'm doing it totally wrong way :( Thanks in advance for any help!
PS: The AJAX success function "$('body').html(data);" allow me visualize the view. Only the body is changed, the url remains the same http://localhost:8000/en/
use javascript window.location.assign and build the url from the form fields.
<script type="text/javascript">
var frm = $('#form_sub');
frm.submit(function (e) {
e.preventDefault();
var name = $('#bk_name').val();
var category = $('#bk_category').val();
var url = '{{ route("search", [":name", ":category"] ) }}';
url = url.replace(':name', name);
url = url.replace(':category', category);
window.location.assign(url);
});
</script>
Please or to participate in this conversation.