jquery - ajax button to show and change status of a DB field - Laravel 4 -
i trying create simple settings panel. want create several buttons, show , change status of options , switch value between 0 , 1. exacly use here in stackoverflow vote answers.
with friendly able create single button, works:
view:
<div class="box_option flexvert invoke2"> @if(isset($userdata) && $userdata->showtoolbar == 1) <a data-remote="true" data-method="post" href="{{ route('switch.toggle_option') }}" id="experiment_update3" class="csh_07"> activated</a> @else <a data-remote="true" data-method="post" href="{{ route('switch.toggle_option') }}" id="experiment_update3" class="csh_11"> not activated</a> @endif </div>
route:
route::post( '/usersettings/ajax_buttons3', array( 'as' => 'switch.toggle_option', 'uses' => 'userworkspacescontroller@toggle_option' ) );
controller:
public function toggle_option() {
$userdata = userworkspace::where('user_id', '=', auth::user()->id)->first();
if($userdata->showtoolbar === 1) { $userdata->showtoolbar = 0; $response = array( 'toggle_update' => trans('messages.un_joined') ); } else { $userdata->showtoolbar = 1; // handles newly created userworkspaces $response = array( 'toggle_update' => trans('messages.joined') ); } $userdata->save(); return response::json( $response ); }
js:
$('a[data-remote=true]').on('ajax:beforesend', function(xhr, settings) { $(this).find('.dropdown-toggle').click(); }); $('a[data-remote=true]').on('ajax:success', function(xhr, data, status) { $(this).text(data.toggle_update); });
problem:
create more one button without cloning code in controller method or js. in sisou's solution controller does't know table want change - link must carry information, right? need c. 20 buttons in single view. thing came out ugly nesting ifs (sorry):
route::post( 'switch/{option}', array( 'as' => 'switch.toggle_option', 'uses' => 'userworkspacescontroller@toggle_option' ) );
and separate if each option/button toggled:
if($option = 1) { if($userdata->showtoolbar == 1) { $userdata->showtoolbar = 0; ... , on...
thx
if want same button change value 1 0 or 0 1, suggest let server-side handle appropriate value , call route (without parameter) button. button be
<a data-remote="true" data-method="post" href="{{ route('join.join_an_action') }}" id="experiment_update">
and controller check value in db , change it:
if($setactionstatus->ajaxtest === 1) { $setactionstatus->ajaxtest = 0; $response = array( 'interface_update' => trans('messages.un_joined') ); } else { $setactionstatus->ajaxtest = 1; // handles newly created userworkspaces $response = array( 'interface_update' => trans('messages.joined') ); } $setactionstatus->save();
as other buttons: need make dom crawling relative link:
$('a[data-remote=true]').on('ajax:beforesend', function(xhr, settings) { $(this).find('.dropdown-toggle').click(); }); $('a[data-remote=true]').on('ajax:success', function(xhr, data, status) { $(this).text(data.interface_update); });
Comments
Post a Comment