Anushka Deshan
Anushka Deshan

Reputation: 81

Ajax send same value but different options in dropdown list

I have a users' data table and im trying to change role of them by populating roles from database to datatable. I use ajax to change the role and it works. but problem is value of selecting option from dropdown is not sent to database.

Herewith I attached my controller function view and ajax code. Please advise me to solve this.

Controller:

public function changeRole(Request $request){
    $id = Input::get('id');
    $isAdmin = Input::get('isAdmin');
    User::findOrFail($id)->update(['isAdmin'=>$isAdmin]);
}

Ajax :

$(document).ready(function(){
$('select').on('change' , function (event){
 id = $(this).data('id');
isAdmin = $('#role').val();
//alert(role);
$.ajax({
    type: 'POST',
    url: SITE_URL + '/changeRole/',

    data: {
        '_token': $('input[name=_token]').val(),
        'id': id,
        'isAdmin': isAdmin

    },
    cache: false,          
    success: function(data) {              
    toastr.success('Admin Role Successfully Changed ! ', 'Congratulations', {timeOut: 5000});
    //$('#example1').DataTable().ajax.reload();           
    },

    error: function (jqXHR, exception) {    
        console.log(jqXHR);
        toastr.error('Something Error !', 'Status not Changed!')
        },
    }); 
}); 
});

View :

<td>
    <form method="post">
     {{ csrf_field() }}
     <div class="form-group">                
         <select class="form-control" data-id="{{$user->id}}" id="role" name="role">
         <option value="0">Select a Role</option>
          @foreach ($roles as $role)
          <option @if($user->isAdmin==$role->id) selected @endif value="{{ $role->id }}">{{ $role->name }}</option>
          @endforeach
          </select>
       </div>  
    </form>          
  </td>

Please see the user table view

Upvotes: 0

Views: 286

Answers (1)

Omar Abdullah
Omar Abdullah

Reputation: 284

First of all don't use Input::get('id') use $request->id and $request->isAdmin

Try dd($request->all()) at the very first line of you changeRole() method and check if you are getting the correct values every time.

Don't use $('select') give your select some id and use it as $('#myselect')

add var before you variable in jquery like var id=$() to keep it in local scope. for reference must read this : https://www.tutorialspoint.com/What-is-the-difference-between-global-and-local-Variables-in-JavaScript

Don't use var id = $(this).data('id'); the .data() messes things up sometimes.

Use it as var id = $(this).attr('data-id');

To get the value of selected roles use following:

var isAdmin = $(this).children("option:selected").val();

Hope this fixes many things.

Upvotes: 2

Related Questions