I am trying to do a post with ajax to laravel. When using the get method it works fine but with the POST, it fails.
Here is the code:
on my app.blade, I have put:
<meta name="csrf-token" content="{{ csrf_token() }}" />
on my view.blade, I have the following ajax code:
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#employeeActivityTable').DataTable( {
ajax: {
url: "{!! route('ajaxactivityperemployee') !!}",
type: "POST"
},
columns: [
{ data: 'employee_id', name: 'employee_id' },
{ data: 'employee_name', name: 'employee_name' },
{ data: 'month', name: 'month' },
{ data: 'sum_task_hour', name: 'sum_task_hour' }
],
columnDefs: [
{
"targets": [ 0 ],
"visible": false,
"searchable": false
}
]
} );
...
I know that my routes are working because I had everything with GET and it worked fine and I only changed it to POST and I get in the troubleshooter tool:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
And here are my routes:
//Employee activity
Route::get('employeeactivity', ['uses'=>'EmployeeActivityController#getView','as'=>'employeeactivity']);
//AJAX
//Activity per employee
Route::get('activityperemployee', ['uses'=>'Ajax\ActivityAjaxController#getActivityPerEmployee','as'=>'ajaxactivityperemployee']);
Route::get('activityperproject', ['uses'=>'Ajax\ActivityAjaxController#getActivityPerProject','as'=>'ajaxactivityperproject']);
Route::post('activityperemployee', ['uses'=>'Ajax\ActivityAjaxController#postActivityPerEmployee']);
and here is the ajax controller:
public function getActivityPerEmployee()
{
$return = $this->activityRepository->getActivityPerEmployee();
$data = Datatables::of($return)->make(true);
return $data;
}
public function postActivityPerEmployee(Request $request)
{
$where = [['col'=>'employee_id','val'=>'13'],['col'=>'month','val'=>'Jan']];
$return = $this->activityRepository->getActivityPerEmployee($where);
$data = Datatables::of($return)->make(true);
return $data;
}
public function getActivityPerProject()
{
$return = $this->activityRepository->getActivityPerProject();
$data = Datatables::of($return)->make(true);
return $data;
}
Again, if in the ajax request, I change the type from POST to GET, everything works fine.
You are trying to send a Post request to a Get Route.
{!! route('ajaxactivityperemployee') !!}"
Related Route is :
Route::get('activityperemployee', ['uses'=>'Ajax\ActivityAjaxController#getActivityPerEmployee','as'=>'ajaxactivityperemployee']);
So in your case you can do somehting like this (give a name to your post route) :
Route::post('activityperemployee','uses'=>'Ajax\ActivityAjaxController#postActivityPerEmployee', 'as'=>'postajaxactivityperemployee']);
and then use your new named route in your ajax call :
{!! route('postajaxactivityperemployee') !!}"
which will call postActivityPerEmployee action
Related
I'm using laravel 8.4 .
My route :
Route::post('test',[\App\Http\Controllers\DataController::class, 'store'])->name('pos-test');
My Controller :
public function store(Request $request)
{
// DB::table('data')->insert('product_code',$request->id);
$badge = explode(' ', $request);
$employee_id = $badge[0];
\DB::table('data')->insert(['product_code'=> $employee_id]);
return response()->json(['success'=>'Product saved successfully.']);
}
Ajax code :
function handleBarcode(scanned_barcode) {
//handle your code here....
console.log(scanned_barcode);
let _token = $('meta[name="csrf-token"]').attr('content');
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('pos-test') }}",
type: "POST", // Can change this to get if required
data: {
code : scanned_barcode,
_token: _token
},
success: function(data) {
$("#status").html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
$("#status").text(textStatus);
console.log(jqXHR);
}
});
};
The request is like this "555444 Razif Raziq" , i would like to explode it so I may insert only "555444" into table but in table column product_code is 'POST' .
The question is how to fix it? thank you
you must explode your correct data in request object not request object itself.
$badge = explode(' ', $request->code);
If the 'code' value is sent correctly, just use this
$request->code
public function store(Request $request)
{
\DB::table('data')->insert(['product_code'=> $request->code]);
return response()->json(['success'=>'Product saved successfully.']);
}
I try to create a relational select option in laravel 8 using ajax but didn't work I get this error in the console: 405 Method Not Allowed
POST http://127.0.0.1:8000/decomptes/%7B%7B%20route(%20'getOperationsChantier'%20)%20%7D%7D 405 (Method Not Allowed)
the route
Route::post('/getOperationsChantier', [DecompteController::class, 'getOperationsChantier'])->name('getOperationsChantier');
the jquery code
$(document).ready(function(){
// When an option is changed, search the above for matching choices
$('#chantiers').change(function(){
$("#mySelect option").remove();
// $("#city option").remove();
var id = $(this).val();
$.ajax({
url : "{{ route( 'getOperationsChantier' ) }}",
data: {
"_token": "{{ csrf_token() }}",
"id": id
},
type: 'post',
dataType: 'json',
success: function( result )
{
$.each( result, function(k, v) {
$('#mySelect').append($('<option>', {value:k, text:v}));
});
},
error: function()
{
//handle errors
alert('error...');
}
});
}).change();
});
the function in the controller :
function getOperationsChantier( Request $request )
{
$this->validate( $request, [ 'id' => 'required|exists:chantiers,id' ] );
$chantierOperations = ChantierOperation::where('chantier_id', $request->get('id') )->get();
$output = [];
foreach( $chantierOperations as $chantierOperation )
{
$output[$chantierOperation->id] = $chantierOperation->operation_id;
}
return $output;
}
can someone help me this is the first time when I use ajax
I used GET method first and I would get this error:
414 (Request-URI Too Long)
My ajax is like this:
var table = $('#datatable').DataTable( {
stateSave: true,
scrollX: true,
serverSide: true,
ajax: {
url: '/lista-evidencija-radnika-po-danu/tabela/'+ id + '/' + tip,
type: 'GET',
data: function ( d ) {
d.zakljucano = $('#zakljucano').val();
},
},...
And my route:
Route::get('/lista-evidencija-radnika-po-danu/tabela/{id}/{tip}', 'EvidencijaRadnikaPoDanuController#tabela_evidencije');
But then i get error: 414 (Request-URI Too Long)
If i switch to POST type adn switch my route to post i will get this error:405 (Method Not Allowed)
var table = $('#datatable').DataTable( {
stateSave: true,
scrollX: true,
serverSide: true,
ajax: {
url: '/lista-evidencija-radnika-po-danu/tabela/'+ id + '/' + tip,
type: 'POST',
data: function ( d ) {
d.zakljucano = $('#zakljucano').val();
},
},...
And my POST route:
Route::post('/lista-evidencija-radnika-po-danu/tabela/{id}/{tip}', 'EvidencijaRadnikaPoDanuController#tabela_evidencije');
My controller
public function tabela_evidencije(Request $request, $id, $tip)
{
$evidencija = EvidencijaRadnikaPoDanu::with('radnik', 'radnik.identifikacija')
->select('evidencija_radnika_po_danus.*', 'radniks.id_identifikacije')
->where('evidencija_radnika_po_danus.id_kompanije', Auth::user()->id_kompanije)
->where('evidencija_radnika_po_danus.id_radnih_dana', $id)
->where('evidencija_radnika_po_danus.tip', $tip);
return datatables()->of($evidencija)
->editColumn('id_radnika', function ($data) {
$puno_ime = $data->radnik->prezime.' '.$data->radnik->ime;
return $puno_ime;
})
->editColumn('id_ime', function ($data) {
return $data->radnik->ime;
})
//pomocu veze izmedju radnika i evidencija pronalazimo identifikacioni broj
->editColumn('id', function ($data) {
return $data->radnik->identifikacija->broj;
})
->editColumn('id_radnika_modal', function ($data) {
return $data->id_radnika;
})
->editColumn('id_modal', function ($data) {
return $data->id;
})
->make(true);
}
After inspecting it while using GET my URL is over 8,000 characters!
I added in my <head> this:
<meta name="csrf-token" content="{{ csrf_token() }}">
and added token in my ajax POST method
ajax: {
url: '/lista-evidencija-radnika-po-danu/tabela/'+ id + '/' + tip,
method: 'POST',
'headers': {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}...
And also changed my route to be post
Route::post('/lista-evidencija-radnika-po-danu/tabela/{id}/{tip}', 'EvidencijaRadnikaPoDanuController#tabela_evidencije');
And i had to run this command in my console
php artisan optimize
In order for my route to change to POST route...
app.jss file
$('#modal-save').on('click', function(){
// geting the properties
$.ajax({
method:'POST',
url: url,
data: {body: $('#post-body').val(), postId: postId , _token: token}
})
// after done
.done(function(msg) {
$(postBodyElement).text(msg['new_body']);
$('#edit-modal').modal('hide')
});
});
my script in view code
<script>
var token = '{{ Session::token() }}';
var url = '{{ route('edit') }}';
</script>
Route file
Route::post('/edit', [
'uses'=>'PostController#postEditPost',
'as'=>'edit'
]);
My controller file
public function postEditPost( Request $request)
{
$this->validate($request,[
'body' => 'required'
]);
// checking auth user
$post = Post::find($request['postId']);
if(Auth::user != $post->user){
return redirect()->back();
}
// updating the post content
$post->body = $request['body'];
$post->update();
return response()->json(['new_body' => $post->body], 200);
}
Your'e sending an ajax request to the server, but dont accept it like so in the controller.
Try this:
// updating the post content
$post->body = $request['body'];
$post->update();
if(request()->expectsJson()){
return response()->json(['new_body' => $post->body], 200);
}
//here you can return to whereever you need it if its not ajax
return redirect('/');
Because of the VerifyCsrfToken middleware, you must provide CSRF token with each post, put, delete request.
Add meta tag inside head tag
<meta name="csrf-token" content="{{ csrf_token() }}">
Then use it in you ajax request
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
See X-CSRF-TOKEN
How can I refresh a page after an ajax call is executed.
My Ajax call is
$.ajax({
type: "POST",
data: data,
url:"{{ path('v2_pm_patents_trashpatents') }}",
cache: false
});
The method that is executed by this ajax is
public function trashpatentAction(Request $request){
if ($request->isXmlHttpRequest()) {
$patent_id = $request->get("pid");
$em = $this->getDoctrine()->getEntityManager();
$patent = $em->getRepository('MunichInnovationGroupPatentBundle:SvPatents')->find($patent_id);
if (!$patent) {
throw $this->createNotFoundException('No patent found for id '.$patent_id);
}
$patent->setIs_deleted(1);
$em->flush();
}
}
Edit
Portfolio Controller Index Action
public function indexAction(Request $request) {
$switch_form = $this->createForm(new SwitchPortfolioType($portfolios));
////rest of action code
return $this->render('MunichInnovationGroupPatentBundle:Portfolio:index.html.twig', array('new_patentgroup_form' => $new_patentgroup_form->createView(),'switch_form' => $switch_form->createView(), 'new_form' => $new_form->createView(), "portfolios" => $portfolios ,"selected_portfolio" => $selected_portfolio,"portfolio_groups" => $portfolio_groups,"patents" => $patents));
}
Index.html.twig
<form name="portfolios" action="{{ path('v2_pm_portfolio') }}" method="post" >
{{ form_widget(switch_form) }}
<input type="submit"class="portfolio_input button2 tooltip" value="Switch">
</form>
SwitchPortfolioType
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class SwitchPortfolioType extends AbstractType
{
public function __construct($portfolios)
{
$this->portfolios = $portfolios;
}
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('', 'choice', array(
'choices' => array(
'test' => 'Test'
),
'empty_value' => 'Switch your Portfolio',
));
}
public function getName()
{
return 'switch_portfolio';
}
}
At the end of this action I want to refresh the page
How can I do this?
The refresh will have to be done in javascript. I am not sure why you would POST via ajax only to reload the page anyway, why not just POST normally?
Anyway, to do what you ask I would return some simple JSON response in the controller to signify a success and then in the ajax callback do this:
$.ajax({
type: "POST",
data: data,
url:"{{ path('v2_pm_patents_trashpatents') }}",
cache: false,
success: function(data) {
// optionally check if the response is what you wanted
//if (data.response == 'deleted') {
document.location.reload(true);
//}
}
});
Using jQUery:
$('your_form').disable=true;
Pure JS:
your_form.disabled = true;