mahmood mahmood - 3 months ago 9
Ajax Question

how to repeat click event in jquery from the beginning as if nothing happened

I want to repeat the same function every time I click in the anchor tag but with new results. for example I have 3 items
a = 0 , b = 0 , c = 1 when I click in th anchor tag for a , b , c I see in th console that : a = 1 ,b = 1 , c = 0 for once and every time I click on these items the same results appear in the console ( a = 1 , b = 1 , c = 0) but when I reload the page and click on the items then it works perfectly so when I click on a it changes to 0 again and the same thing for the rest two items so ( when I click again after refresh the page : b = 0, c =1) Now... I want to do that without reloading the page so when I click on the item a ( a = 0 for example) it should change to ( a = 1 ) click again ( then a = 0 ) and thanks in advance

/////////// my jquery ///////////////////

$('.admin-btn').on("click",function(event){
event.preventDefault();
var userId = event.target.parentNode.parentNode.childNodes[1].textContent;
var admin = 0;
var isAdmin = event.target.dataset['isadmin'];

if(admin == isAdmin){
admin = 1;

$.ajax({
method:'POST',
url:makeAdminUrl,
data:{ Admin:admin , userId:userId , _token:token}
})
.done(function(msg){
console.log(msg['Admin']);
});
});


/////////// html ///////////

@extends('cp.master')

@section('title','users')

@section('page-content')

<div class="row" style="margin-top:20px;">
<div class="col-md-12">
<table class="table">

<thead>
<th>#</th>
<th>Name</th>
<th>Created at</th>
<th>Action</th>
</thead>

<tbody>
@foreach($users as $user)
<tr>
<th>{{ $user->id }}</th>
<td>{{ $user->username }}</td>
<td>{{ $user->created_at }}</td>
<td>
<a data-isadmin="{{ $user->admin }}" href="#" class="btn btn-primary admin-btn">Admin</a>
<a href="#" class="btn btn-danger ban-btn">Ban</a>
</td>
</tr>
@endforeach
</tbody>

</table>
</div>
<div class="text-center">
{{ $users->links() }}
</div>
</div>
<script type="text/javascript">
var makeAdminUrl = '{{ route('makeAdmin') }}';
var token = '{{ Session::token() }}';
</script>
@endsection




////////// my controller //////////

public function postAdmin(Request $request)
{
$user = User::find($request['userId']);
$user->admin = $request['Admin'];
$user->update();

return response()->json(['Admin' => $request['Admin']]);
}

Answer

I assumed your problem as per your description in the question.

Try this example, it may helps you.

Do the necessary changes as per your need.

$('.dummy-class').click(function(){
  //Get the current value, check condition and change the value
  var temp = $(this).text() == 0 ? 1 : 0;
  //Set the new value
  $(this).text(temp)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A = <a href="#" class="dummy-class">0</a>
B = <a href="#" class="dummy-class">0</a>
C = <a href="#" class="dummy-class">1</a>