Loop in Script not working

62 views Asked by At

I'm trying to redirect a user after a onclick action but the userid in the following code always remains the same regarless the user chosen in the table. Maybe I'm missing something here...

<td>
  <?php if ($memberinfo['UserIsChecked'] == 1){ ?>
    <button class="btn btn-xs btn-icon btn-default"> <i class="fa fa-times"></i> </button>
  <?php } else { ?>
    <a href="#"><p onclick="go()">Approve/Refuse <?php echo($memberinfo['UserId']) ;?></p></a>
    <script>
      var userid='<?php echo $userid;?>';
      function go(){
        swal({
          title: 'Are you sure?',
          text: "You won't be able to revert this!",
          type: 'warning',
          showCancelButton: true,
          confirmButtonText: 'Validate user',
          cancelButtonText: 'Refuse request',
          confirmButtonClass: 'btn btn-success',
          cancelButtonClass: 'btn btn-danger m-l-10',
          buttonsStyling: false
        }).then(function () {
          swal(
            'User validated!',
            'The user has been notified.',
            'success',
          ).then(function(){
            window.location = 'scripts/process-validate-user.php?userid='+ userid +' ' ;
          })
        }, function (dismiss) {
          // dismiss can be 'cancel', 'overlay',
          // 'close', and 'timer'
          if (dismiss === 'cancel') {
            swal(
              'User refused',
              'The user has been notified.',
              'error'
            )
          }
        })
      }
    </script>
  <?php } ?>
</td>
2

There are 2 answers

1
Marcin Malinowski On

are you iterating over columns or rows in that table? if so then you are probably redeclaring and reinitializing userid as well as the go() function itself in global scope.

try adding an x-userid="" attribute to anchor tags where you bind go() function. Then in the go function would start as follows:

function go(event) { var userid = event.target.getAttribute('x-userid'); ... }

2
Bassem Shahin On

if those are table rows, then you can simply add a hidden <div> as in after <tr> as below:

<td>
<?php if ($memberinfo['UserIsChecked'] == 1){ ?>
    <button class="btn btn-xs btn-icon btn-default"> <i class="fa fa-times"></i> </button>
<?php } else { ?>
    <span style="display:none" class="user-id"><?php echo($memberinfo['UserId']) ;?></span>
    <a href="#"><p onclick="go()">Approve/Refuse <?php echo($memberinfo['UserId']) ;?></p></a>

Then, in the JavaScript code, get this <span> text by JavaScript or jQuery relative to the user’s click.