405 (Method Not Allowed) error on ajax in Laravel 8 - ajax

I am trying to call an ajax function in my Laravel 8 Project. But on every call I am getting error POST http://127.0.0.1:8000/getReasonForVisit 405 (Method Not Allowed). I have tried many options like changing post method to get, change url etc. but no use. It would be helpful if someone can help me.
Here is my code.
JS File
function getReasonForVisit(catId) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url : '/getReasonForVisit',
data : {'catId' : catId },
dataType: 'json',
success:function(data) {
console.log(data);
}
});
}
$('#treatment-category').on('change', function (){
var catId = $(this).val();
getReasonForVisit(catId);
});
View
<select class="form-control form-select" name="category" id="treatment-category">
<?php $categories = App::make("App\Http\Controllers\AppointmentsController")->getTreatmentCategories(); ?>
#foreach($categories as $cat)
<option value="{{ $cat->id }}">{{ $cat->category_name }}</option>
#endforeach
</select>
Route
Route::post('/getReasonForVisit', [App\Http\Controllers\AppointmentsController::class, 'getReasonForVisit'])->name('getReasonForVisit');
Controller
class AppointmentsController extends Controller
{
public function getTreatmentCategories() {
$categories = DB::table('treatment_category')->get();
return $categories;
}
public function getReasonForVisit() {
echo 111;
}
}
EDIT
I did cleared my route cache. now it's showing error CSRF token mismatch

Please change option type to method
$.ajax({
method: 'POST',
url : '/getReasonForVisit',
data : {'catId' : catId },
dataType: 'json',
success:function(data) {
console.log(data);
}
});

I resolved my issue. Actually I am missing csrf meta tag in my blade. So Now I added this code in view blade file in the <head> tag.
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>

Related

how send id in ajax for laravel

i want to run my ajax after click on one of the options in select tag. and send id of option to ajax url.
please help me . these are my codes.
#foreach($emails as $mail)
<option id="{{$mail->id}}">{{$mail->email}}</option>
#endforeach
</select>
my ajax
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.select option').on('click',function () {
var id=$('.select option:selected').attr("id");
$.ajax({
url:'/mailactive',
type:'get',
dataType:'json',
data:{id:id}
})
})
})
try to use this:
give to your select an id, for example id_select
use #id_select > option:selected in your jQuery selector instead of .select option:selected
then tell me if you still can't get the id
In Your Laravel Blade
<select id="email">
#foreach($emails as $mail)
<option id="{{ $mail->id }}"> {{ $mail->email }} </option>
#endforeach
</select>
If your Route is POST method
$(document).ready(function () {
var id = $('#email').children(":selected").attr("id");
$.post('{{ url('your_POST_route_url') }}', {
'_token': "{{ csrf_token() }}", id:id,
}, function (data) {
console.log(data); // Print your response into your console
});
});
If your Route is GET method
$(document).ready(function () {
var id = $('#email').children(":selected").attr("id");
$.get('{{ url('your_GET_route_url') }}', {
id:id,
}, function (data) {
console.log(data); // Print your response to your console
});
});
You should have return data from your GET or POST method.

How to get data from controller to view using ajax in codeigniter

View:
<select class="form-control" id="emp_id" name="emp_id">
<option value="">--- Select Emp id ---</option>
<?php foreach($employee as $emp){?>
<option value="<?php echo $emp->id;?>"><?php echo $emp->id;?></option>
<?php }?>
</select>
<div id="home"></div>
<script>
$('select[name="emp_id"]').on('change', function() {
var id=$("#emp_id").val();
$.ajax({
url: "<?php echo base_url(); ?>/employee_master"+id,
dataType: 'json',
type: 'post',
success: function(data) {
alert("hi");
console.log(data.res);
},
error: function( error )
{
alert( error );
}
});
return false;
});
</script>
Controller:
public function employee_master($id)
{
$data['res']=$this->payslip_model->fetch_employee_name($id);
echo json_encode($data);
}
Model:
public function fetch_employee_name($id)
{
$this->db->select('name');
$this->db->from('employee_master');
$this->db->where('id',$id);
$res=$this->db->get();
return $res->result();
}
In above code,I am using dataType:'json' in ajax, it will always execute error function in ajax.If I am not using dataType:'json' it works fine, but I cannot know how to retrieve the data from controller to ajax.Please help me to find out the error.
yes it will give you error when you use data type json. it means that on ajax call the data will be pass to controller in json format..
while you are passing a simple post data...
remove the datatype json. every thing is ok...
and more mistake use this line
url: "<?php echo base_url(); ?>/contorller_name/employee_master/"+id,

ajax post with laravel 5.6

I can't figure out how to get this ajax request to post.
<button class="btn btn-sm btn-primary" id="ajaxSubmit">Submit</button>
<textarea rows="4" class="form-control resize_vertical" id="application_notes" name="application_notes" placeholder="Notes">{{$application->notes}}</textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var url = "/instructor-notes-save/{{$application->id}}"
$(document).ready(function(){
$('#ajaxSubmit').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: url,
method: 'post',
data: {
application_notes: jQuery('#application_notes').val(),
},
success: function(response){
console.log(response);
}});
});
});
</script>
My controller is this:
public function saveNotes(Request $request, $id)
{
$application = Application::findOrFail($id);
$application->notes = $request->application_notes;
$application->save();
return response()->json(['success'=>'Data is successfully added']);
}
And for what it's worth, here is my route:
Route::post('/instructor-notes-save/{id}', 'InstructorsController#saveNotes')->name('instructor.save.note');
What am i missing to get this ajax request to work? In my console log, i get a 419 unknown status error.
Kindly check that the meta tag _token is present in your layout file inside the <head> tag.
Also please make sure that the AJAX url is present in your routes file.
add the following tag in your html <head>:
<meta name="csrf-token" content="{{ csrf_token() }}">

Request of Ajax with Laravel 5.4

I am trying to make an example of Ajax request with Laravel 5.4.
The test example is simple, just enter a numeric value in an input = text field in my View and leave the field to send to the Controller, then add + 10 to that value and then return that value to my View so that it can displayed on an alert.
HTML : viewteste.blade.php
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<form action="">
Valor: <input type="text" id="valor" name="valor" />
</form>
</body>
</html>
JS: The js file is inside viewteste.blade.php, I just split it to make it easier to interpret.
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$("#valor").on('blur', function()
{
valor = $(this).val();
$.ajax({
type:'POST',
url:"{{ URL::to('/teste/valor') }}",
dataType: 'JSON',
data: {
"valor": valor
},
success:function(data){
alert('Success');
},
error:function(){
alert('Error');
},
});
});
});
</script>
Route
Route::get('/teste', 'TesteAjaxController#index');
Route::post('/teste/valor', 'TesteAjaxController#valor');
Controller
class TesteAjaxController extends Controller
{
public function index()
{
return view('painel.viewteste');
}
public function valor(Request $request)
{
$valor= $request->input('valor');
$valor += 10;
return $valor; // How do I return in json? in case of an error message?
}
}
Always when I try to send the request via ajax it goes to alert ('Error'). is it that I'm doing something wrong in sending the ajax or route?
to return a json response. you need to use.
response()->json([
'somemessage' => 'message',
'valor' => $valor
]);
UPDATE: you are getting an error alert because i think your route method doesnt match your controller methods.
Route::post('/teste/valor', 'TesteAjaxController#valor');
where in your controller you have
public function cep() ...

Laravel 4.2 ajax pagination Routing Issue

Showing this message in console
GET http://localhost/ajax/pagination?page=5 404 (Not Found)
View page (pages.post) :
#foreach ($posts as $post)
<article>
<h2>{{ $post->title }}</h2>
</article>
#endforeach
{{ $posts->links() }}
<script>
$(document).ready(function() {
$(document).on('click', '.pagination a', function (e) {
getPosts($(this).attr('href').split('page=')[1]);
e.preventDefault();
});
});
function getPosts(page) {
$.ajax({
type:'GET',
url : '/ajax/pagination?page=' + page,
}).done(function (data) {
$('.posts').html(data);
location.hash = page;
})
}
</script>
Route :
Route::get('/ajax/pagination',array('before' =>'auth' ,
'uses'=>'CampaignsController#showPostspag'));
Controller :
public function showPostspag()
{
$posts = Address::paginate(5);
return View::make('pages.post')->with('posts',$posts);
}
Where is my mistake? I think that is ajax url and routing problem..
Try this..
if "ajax" your root directory means update following code
function getPosts(page) {
$.ajax({
type:'GET',
url : 'pagination?page=' + page,
}).done(function (data) {
$('.posts').html(data);
location.hash = page;
})
}
Route :
Route::get('pagination',array('before' =>'auth' ,
'uses'=>'CampaignsController#showPostspag'));

Resources