Saturday, March 4, 2023

 To change a flag from 1 to 0 using AJAX from a table where all data is listed in Laravel, you can follow these steps:

  1. In your view, add a button or a link that will trigger the AJAX request when clicked. For example:
html
<button class="btn btn-danger" data-id="{{ $record->id }}">Deactivate</button>
  1. Add JavaScript code to your view that will handle the button click event and send the AJAX request to the server. For example:
javascript
$('button').click(function() { var id = $(this).data('id'); $.ajax({ url: '/deactivate', type: 'POST', data: { id: id, _token: $('meta[name="csrf-token"]').attr('content') }, success: function(response) { // Handle the response from the server } }); });
  1. In your controller, create a method that will handle the AJAX request and update the flag in the database. For example:
php
public function deactivate(Request $request) { $id = $request->input('id'); $record = YourModel::find($id); $record->flag = 0; $record->save(); return response()->json(['success' => true]); }

Note: In the above example, replace YourModel with your actual model name. Also, make sure to include the CSRF token in your AJAX request by adding the following meta tag to your view:

html
<meta name="csrf-token" content="{{ csrf_token() }}">

And include the following line of code in your JavaScript code:

javascript
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },

Route::post('/deactivate', 'YourController@deactivate')->name('deactivate');

Note: Replace YourController with your actual controller name.

This route will handle the AJAX request sent by the JavaScript code and call the deactivate method in your controller.

No comments:

Post a Comment

How to Host a Laravel Project on Hostinger’s hPanel: A Step-by-Step Guide

How to Host a Laravel Project on Hostinger’s hPanel: A Step-by-Step Guide If you're looking to host a Laravel project on Hostinger’s hPa...