Post data on database with ajax laravel - ajax

I have a counter in Ajax and I would like to save the value of the counter in a database so that the value of the counter continues to grow even when the user disconnects or refreshes the page. I use the laravel framework. how to do it, please?

Add the csrf_token() to somewhere on the blade view:
<input type='hidden' name='_token' value='{{ csrf_token() }}' id="csrf">
Add this route to your routes/web.php file:
Route::post('add-to-counter', 'YourController#add');
Your php script:
public function add()
{
// retrieve de counter value from the database:
$i = DB::table(...)->select(...)->get();
$i = ++$i;
// and save it to the database
return response()->json([
'data' => $i
]);
}
Then, create a ajax request:
let _token = $("#csrf").val();
$.ajax({
url: 'add-to-counter',
method: 'post',
data: {
'_token': _token,
}
success: function(response){
// What happens if the ajax request finishes successfully
alert("The current counter value is: "+response.data);
}
});

Related

Laravel Redirect doesn't function similar when called from two different methods

I'm trying to click on a button and load the previous month data onto the screen. Initially it passes the current month and year and the page load works fine. Since the nav button click could be done in any month there it calculates the new month and passes to the same method. But the page load after each button click only returns the response, doesn't display data on screen. Can you please help me to find what causes this issue and sort this out. Here are my code snippets.
jquery
$(".month-nav-left").click(function(e){
e.preventDefault();
// currently hard coded - just to check
var month = 8;
var year = 2024;
var monthDir = "mBack";
$.ajax({
type:'POST',
url:"{{ route('monthBack') }}",
data:{month:month, year:year, monthDir:monthDir},
success:function(data){
// alert(data.success);
// console.log(data);
}
});
routes
use App\Http\Controllers\CalendarSetupController;
Route::get('/', [CalendarSetupController::class, 'index']);
Route::get('/{year}/{month}', [CalendarSetupController::class, 'monthToDisplay'])->name('selectCalendar');
Route::post('/mback', [CalendarSetupController::class, 'selectMonth'])->name('monthBack');
controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class CalendarSetupController extends Controller
{
public function index()
{
$month = (int)date('m');
$year = (int)date('Y');
// This displays data correctly on initial load.
return \Redirect::route('selectCalendar', [$year, $month]);
}
public function monthToDisplay()
{
$year = request()->segment(1);
$month = request()->segment(2);
$list=array();
$month=(date("F", mktime(12, 0, 0, $month, 1, $year)));
return View::make('mainPage', ['date' => $list, 'month' => $month, 'year' => $year]);
}
function selectMonth(Request $request)
{
$input = $request->all();
$month = $input["month"];
$year = $input["year"];
switch($input["monthDir"])
{
case "mBack":
$month = (int)strftime('%m', strtotime('+1 month', mktime(0, 0, 0, $month, 1, $year)));
break;
}
// This only have the correct view in the response, but does not load on the screen.
return \Redirect::route('selectCalendar', [$year, $month]);
}
}
Thank you.
monthBack is a web route and all requests that target it will pass throught the VerifyCsrfToken middleware which checks for a valid token.
Since your ajax request includes no valid _token key it will be rejected (unauthorized, You can see the HTTP answer in your live artisan serve log).
If you didn't edit your HTML layout the header will already include a valid token.
<meta name="csrf-token" content="{{ csrf_token() }}" />
Here is how to add that token to your POST request:
$.ajax({
type: "POST",
url: "{{ route('monthBack') }}",
data: {
month:month, year:year, monthDir:monthDir,
_token:$('meta[name="csrf-token"]').attr('content')
},
success: success,
dataType: dataType
});
Or add
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
Note that the token stays valid for a limited period of time, if you do not refresh your page for a while the button will not work.
I added a line to redirect to the desired url in the javascript code. I am not sure if it's a best practice or not, but it did as expected. Thank you for your time.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".month-nav-left").click(function(e){
e.preventDefault();
// currently hard coded - just to check
var month = 8;
var year = 2024;
var monthDir = "mBack";
$.ajax({
type:'POST',
url:"{{ route('monthBack') }}",
data:{month:month, year:year, monthDir:monthDir},
success:function(data){
// alert(data.success);
// console.log(data);
}
});
window.location.replace("http://127.0.0.1:8000/"+year+"/"+month);
});
What happens if you try the helper function redirect()->route('route.name', 'data' => $data); instead of using the \Redirect::route() static method?

how to eliminate with ajax and laravel?

I need to delete a column using ajax and laravel so far I have the following but it does not work for me thanks,
I send a route to the post, this route I get from the path attribute of the button
view()
<button id="eliminarArticulo" ruta = "{{URL::to('auto/eliminarArticulo')}}" onclick="eliminarArticulo({{$detalle_modelo->idetalleModelo}})" class="btn btn-outline btn-danger"><i class="fa fa-trash"></i></button>
js(ajax)
<script>
function eliminarArticulo(id) {
var ruta = $('#eliminarArticulo').attr('ruta');
var url = ruta+"/"+id;
// alert(url)
$.post({
url: url,
data: {id:id},
dataType: 'json',
success : function (res) {
// console.log(res);
}
});
}
</script>
Ruta
Route::group(['prefix' => 'auto'], function(){
Route::get('crear', 'AutoController#crear')->name('auto.crear');
Route::post('registrar', 'AutoController#registrar')->name('auto.registrar');
Route::get('listar', 'AutoController#listar')->name('auto.listar');
Route::get('editar/{cod}', 'AutoController#editar')->name('auto.editar');
Route::post('actualizar', 'AutoController#actualizar')->name('auto.actualizar');
Route::get('ver/{cod}', 'AutoController#ver')->name('auto.ver');
Route::post('guardarArticulo', 'AutoController#guardarArticulo')->name('auto.guardarArticulo');
Route::get('editarArticulo/{cod}', 'AutoController#editarArticulo')->name('auto.editarArticulo');
Route::post('actualizarArticulo', 'AutoController#actualizarArticulo')->name('auto.actualizarArticulo');
Route::post('ActualizarEstadoAuto/{cod}', 'AutoController#ActualizarEstadoAuto')->name('auto.ActualizarEstadoAuto');
Route::post('eliminarArticulo/{cod}', 'AutoController#eliminarArticulo')->name('auto.eliminarArticulo');
});
controlador
public function eliminarArticulo(Request $request){
return $request;
}
Please feel free to correct my grammar because it's terrible
This is how I made my ajax delete function.
When the user clicks on the button it will trigger the onclick event I'm passing in the Id with onclick="deleteRmaMarketplace({{ $rmaMarketplace->id }}).
Here is my button once the user clicks on the button it will call the deleteRmaMarketplace() function also note that I'm passing the MarketplaceId into the function parameters like this deleteRmaMarketplace({{ $rmaMarketplace->id }})
<button class="btn btn-danger rm-marketplace" type="button" onclick="deleteRmaMarketplace({{ $rmaMarketplace->id }})">
<i class="fa fa-trash"></i>
</button>`
Here is my route I'm using named routes because it's easier and I'll use the named routes for my JavaScript variable.
Route::post('/rma-returnType-delete', 'AdminSettings\AdminSettingsController#rmaReturnTypeDelete')->name('admin.rma.returnType.delete');
Here is the JavaScript function I made first I made a variable called deleteRmaReturnTypeUrl and I gave it the value of my route like this '{{ route('admin.rma.returnType.delete') }}'; I can use this for the Url in the ajax function next I made a variable called token and I gave it the value of the '{{ csrf_token() }}'; you'll need it because all post requests required the token in laravel
var deleteRmaReturnTypeUrl = '{{ route('admin.rma.returnType.delete') }}';
var token = '{{ csrf_token() }}';
function deleteRmaMarketplace(Id) {
$.ajax({
url: deleteRmaMarketplaceUrl,
type: 'post',
data: {Id: Id, _token: token},
dataType: 'json',
success:function () {
location.reload();
}
});
}
Here is my controller code
First, we check if the request is ajax and then I make a variable called $ticketId and give it the value of the Id we posted from the ajax request next I made a variable $ticket and I get the RmaReturnType where the id = to the ticketId variable then we delete the ticket by calling $ticket->delete() and then we return the response
public function rmaReturnTypeDelete(Request $request)
{
if ($request->ajax()) {
$ticketId = $request->input('Id');
$ticket = RmaReturnType::where('id', $ticketId)->firstOrFail();
$ticket->delete();
return response()->json($ticket);
}
return response()->json('error', 422);
}

Delete a record without using form in laravel

Need to delete a record without using form tag. Just pass a id in url and get a id need to process.
Thanks
follow below steps
HTML
Delete
JS
$('a#btnDelete').on('click',function()
{
var thisElement = $(this);
$.ajax({
type: 'post',
url: "{{url('/')}}" + '/deleteRecord/'+thisElement.attr('thisRecordId'),
data : {'_token': '{!! csrf_token() !!}'},
async: false,
success:function(response)
{
console.log(response)
}
});
});
Route
Route::post('deleteRecord/{id}','YourController#deleteRecord');
Controller
public function deleteRecord($id)
{
$findRecord = ModelName::findOrFail($id);
$findRecord->delete();
return 'success';
}
hope you will find your solution !
Try like this
<a type="button" class="label label-danger" href="/user/delete/{{$user->id}}">Delete</a>
Controller method
public function getDelete($id)
{
echo $id;
}

updation issue during with ajax method

i am trying to update my record with ajax and i don't know here i am doing wrong the code with my ajax:
$(document).ready(function(){
$('.edit_tag_button').click(function(){
var id = $(this).parent().find('.tag_id').val();
var formData = {
'tag_type' : $('#tag_type').val(),
'quantity' : $('#quantity').val(),
'number' : $('#number').val(),
'active' : $('#active').val(),
'issued' : $('#issued').val(),
};
$.ajax({
url: "{{url('')}}/update/tagslist/"+id,// Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
success: function(data) {
swal("Success!", "Great Job!! Your data has been updated","success");
location.reload();
},
error: function () {
swal("Error", "Look like We got some problem. Can you please refresh the page and try again" , "error");
}
});
});
});
and my controller code is:
public function updateTags(Request $request,$id)
{
$plan = Tags::where('id',$id);
$plan->update($request->all());
}
it says your values updated successfully but it does update my values any help plz
In Laravel POST method required CSRF protection.
Make sure to add meta with csrf token content
<meta name="_token" content="{{ csrf_token() }}">
And share it to ajax setup.
$.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}});

Laravel ajax 500 (Internal Server Error)

I am trying to do an ajax call in laravel. The ajax call logs my data how I want it, but keeps giving me the 500 error. I've read that you need to set the _token in the data field. But that doesn't work for me. So, I can log all the data, but ones I want to push it to the DB I keep getting this error.
Here's my code.
Script.js
$('.likeBtn').click(function(e){
e.preventDefault();
var userid=$(this).siblings('input[name=userID]');
console.log(userid[0].value);
var useridarticle=$(this).siblings('input[name=userIdFk]');
console.log(useridarticle[0].value);
var articleid=$(this).siblings('input[name=articleId]');
console.log(articleid[0].value);
var token=$(this).siblings('input[name=_token]');
console.log(token[0].value);
$.ajax({
url:"articles" ,
type: "post",
data: {'user_id':userid[0].value,
'article_id':articleid[0].value,
'user_id_fk':useridarticle[0].value,
'_token': token[0].value},
success: function(data){
console.log(data);
}
});
});
Controller.
if(Request::ajax()) {
$data = Input::all();
print_r($data);
}
My tokens are set in the header of my master.blade
<meta name="_token" content="{!! csrf_token() !!}"/>
And at the end of my master.blade
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
What am I not seeing? FYI, You might ask why I need does variables. I need them because I generate the same form in a foreach. This works fine for me, i get the data that I want so.

Resources