Laravel Ajax Button

in blade

<button class="btn-xs btn-info grant_access" data-options='{"user_id":"{{ $user->id }}", "action": "remove", "role_id" : {{ $role_id }}, "_token": "{{ Session::token() }}" }'>Has Access<h;/button>

<script>
$('.grant_access').click(function(){
	var options = $(this).data( "options");
	var sel = $(this);
	
	//console.log(options);
	$.ajax({
		method: 'post',
		url: '/pat-admin-access',
		data: options,
		dataType: 'JSON',
	}).done( function( response ) {
		//console.log(response);
	    if (response['result']) {
	    	sel.addClass((response['action'] == 'grant')?  'btn-info' : 'btn-warning');
	    	sel.removeClass((response['action'] == 'grant')? 'btn-warning' : 'btn-info');

	    	sel.text((response['action'] == 'grant')  ? "Has Access" : "Grant Access");
	    	sel.data('options').action = (response['action'] == 'grant') ? 'remove' : 'grant';
	    } else {
	    	sel.text('There was problem');
	    }
	    

	});
		


});							
</script>

in route

Route::post('/pat-admin-access/', [
   'middleware' => 'AppControl:pat-admin-access',
    'redirect' => 'request_access',
    'uses' => 'PatController@updateUserForAdminControl'
])
->name('pat-admin-access')
;

in controller

public function updateUserForAdminControl(Request $request) {
        // $data = $request->only('action', 'user_id', 'role_id');
        $data = $request->all();
        if ($data['action'] == 'grant') {
            \DB::table('role_users')->insert([
                'user_id' => $data['user_id'],
                'role_id' => $data['role_id']
            ]);
        } else if ($data['action'] == 'remove') {
            \DB::table('role_users')
                ->where('user_id', '=', $data['user_id'])
                ->where('role_id', '=', $data['role_id'])
                ->delete();
        }

        return $response = ['action'=>$data['action'], 'msg'=>'success', 'result' => true];

    }

You may also like...