How to pass a variable parameter to jquery

Asked

Viewed 345 times

1

Well, I have a button that when clicked should open another page, by clicking via Ajax the results of the bank. The problem is I have to pass an id through that button for the Ajax request. Making an analogy is like a button that would load a page with all the comments from an article. The id I should pass is the article id. In Ajax I take this article id and send it to my controller to do the query and return Json. Example of the button:

 <div class="btn-group" role="group">
    <a href="/projeto/fazer" data-id="{{$artigo->id}}" class="btn btn-default"><span class="glyphicon glyphicon-fire"></span> Fazer</a>
</div>

Example of how I am loading the result via ajax:

$(document).ready(function() {

var artigo_id =  $(this).data('id'); //esse ID que quero receber do botão

$.ajax({
    type: 'GET',
    url: '/carrega/comentarios/artigo/' + artigo_id,
    data: {
        '_token': $('input[name=_token]').val(),
    },
    success: function (data) {



        for (var i =0; i<data.length;i++){.........
  • Your question is very wide, try to put the snippet of code to which you had difficulty.

  • Place Techo’s HTML code and Javascript’s button and events

  • Good evening posted an example of the code.

  • js is in a separate file.

1 answer

0

This way you won’t get the id. You’re not referencing the tag <a>.

Do so:

<div class="btn-group" role="group">
    <a href="/projeto/fazer" data-id="{{$artigo->id}}" class="btn btn-default btn-article"> 
    <span class="glyphicon glyphicon-fire"></span> Fazer</a>
</div>

Inside the Document.ready:

$('a.btn-article').click(function(e) {
    e.preventDefault(); // previnir da página ser carregada
    var artigo_id = $(this).data('id');
});

Remembering that you can put the url in href as well. Dai would pass the whole url in ajax:

$(this).prop('href');

Browser other questions tagged

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