How to pass a parameter from laravel to jquery

1

Well, I have a button that when clicked should open another page, loading via Ajax the results of the bank. The problem is that I have to pass an id by that button to the Ajax request. Making an analogy is like a button that would load a page with all the comments of an article. The id that I must pass is the id of the article. In Ajax I get this article id and I give my laravel controller the query and return the Json. Button example:

 <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'm 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++){.........
    
asked by anonymous 07.05.2018 / 23:51

1 answer

0

This way you will not get the id. You are not referring to the <a> tag.

Do this:

<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 too. Dai would pass the entire url in ajax:

$(this).prop('href');
    
08.05.2018 / 14:45