onclick inside <a> tag does not work

Asked

Viewed 759 times

0

I have a link inside an array in which I do a json_encode and send to an html table, and inside the tag I have a function inside the onclick that should be send an ajax request and do the preventDefault() not to redirect the page, but when I click the action is not executed and the page is redirected to the address on the link.

Below the code in PHP and javascript

Snippet of PHP code with the array that loads the data and has the link

while($stm->fetch())
           {
               $retorno[] = array("id"=>$col_id,"cnpj"=>$col_cnpj,"razaoSocial"=>$col_razao_social,"nomeFantasia"=>$col_nome_fantasia,"cep"=>$col_cep,"cidade"=>$col_cidade,"celular"=>$col_celular,"telefone"=>$col_telefone,"telefoneDois"=>$col_telefone_dois,"bairro"=>$col_bairro,"rua"=>$col_rua,"numero"=>$col_numero,"observacao"=>$col_observacao,"estado"=>$col_estado,"botao"=>"<a  href='../controller/moduloFornecedoresController/FornecedoresController.php?p=excluirFornecedor&id=".$col_id."' class='btn btn-danger btn-bordered exclui_fornecedor' role='button' title='Excluir' onclick='ajaxGenericoNoData('.exclui_fornecedor')'><i class='far fa-trash-alt'></i>Excluir</a>");
           }

Javascript function (inside onclick)

function ajaxGenericoNoData(classe){

$(classe).click(function(e){

    e.preventDefault();

    $.ajax({
        type:"POST",
        url:$(classe).attr("href"),
        success:function(mensagem)
        {
            console.log(mensagem);
        }
    });
});

}

1 answer

0


But you want to do this AJAX via the eventListener you create in Javascript, or via the call of the function you make in the onclick?

No need to create a eventListener if you are already calling a function in the onclick, but you need to stop the default anchoring behavior, which is redirect to the new page.

Like the attribute onclick does not generate a evento, can not use evento.preventDefault(), for these cases, just return false in the anchor code itself, as in the example below:

function ajaxGenericoNoData(classe) {
  console.log('A página não foi redirecionada');
  
  $.ajax({
    type: "POST",
    url: $(classe).attr("href"),
    success(mensagem) {
      console.log(mensagem);
    },
    error(err) {
      console.log('Porém essa requisição não é válida no SO');
    }
  });
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a
  href='../controller/moduloFornecedoresController/FornecedoresController.php?p=excluirFornecedor&id=".$col_id."' 
  class='btn btn-danger btn-bordered exclui_fornecedor' 
  role='button' 
  title='Excluir' 
  onclick='ajaxGenericoNoData(".exclui_fornecedor"); return false;'
>
  <i class='far fa-trash-alt'></i>
  Excluir
</a>;

  • It worked out, thank you very much. That’s right I wanted to run the ajax inside the onclick.

Browser other questions tagged

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