Jquery and PHP POST method

Asked

Viewed 1,417 times

0

Dear colleagues.

I have a button on the bootstrap:

<button class="btn btn-xs btn-primary active" name="Botao" value="Ativar" id="ativar">Ativar</button>

I would like that by clicking this button, the status was changed to Deactivate, but without refreshing the page. I’m using the code below to direct to the page that makes the change, but it doesn’t seem to be going. See:

$(document).ready(function() {
    $('#ativar').click(function() {
    var valor = $(this).attr('value');
     $.ajax ({
            type: "POST",
            url: "alterar.php?Key="+valor,
             data:  datastring
      })
    });
  });

The change in PHP is OK when I go straight to the change.php page, but from the button it seems that you are not seeing the page.

  • I recommend reading http://api.jquery.com/jquery.ajax/ part of success.

  • What page is this Javascript running on? Do you want to change the status on the same page or on future pages?

2 answers

1

Try this:

    $(document).ready(function() {
            $('#ativar').click(function(e) {
            e.preventDefault();
            var valor = $(this).attr('value');
             $.ajax ({
                    type: "POST",
                    url: "alterar.php",
                    data: {key: valor},
                    cache: false,
                    success: function(result) {
                 }
              })
            });
          });

1


ARQUIVO JS

var valor = jQuery('button.active').val();

jQuery.ajax({
    url : "alterar.php?Key="+valor,
    dataType : 'json',
    async : false,
    success : function(msg) {
        if(msg.status == 1){
            jQuery('button.active').html('Ativo').val('Ativo');
        }else{
            jQuery('button.active').html('Desativado').val('Desativado');
        }
    }
});

Arquivo PHP

$return = array('status'=>null);
if($_GET['Key'] == 'Ativo'){
    $return['status'] = 0;
}else{
    $return['status'] = 1;
}

die(json_encode($return));
  • Thanks to all the colleagues who helped. On the button, to pass the user ID, I used this way: value="<? php echo $idUsuarios; ? >". So I took the value of the ID passed by the button.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.