简体   繁体   中英

Jquery named function not working as callback

Maybe this is a dumb question but i cannot understand why is happening

I have this jquery code:

    $(document).ready(function(){
        // Coloca datos JSON en sus respectivos campos
        function setData(data){
            $('#id').val(data.id);
            $('#name').val(data.name);
            $('#status').val(data.status);
            $('#rating').val(data.rating);
            $('#description_short').val(data.description_short);
            $('#description_long').val(data.description_long);
            image_url = (data.image_url) ? data.image_url + "?" + new Date().getTime() : 'https://via.placeholder.com/512';
            $("#image").attr('src', image_url);

            $('button[name=btn-delete]').prop('disabled', false);
        };


        $('button[name=btn-edit]').click(function(){
            $('#modal-form').attr('action', "{{route('categories.index')}}/" + $(this).data('id'));
            $.get("{{route('categories.index')}}/" + $(this).data('id') + "/edit")
            .done(function (data){
                setData(data);
        });
    });

Its working prefectly as intended, but if i do this:

        $('button[name=btn-edit]').click(function(){
            $('#modal-form').attr('action', "{{route('categories.index')}}/" + $(this).data('id'));
            $.get("{{route('categories.index')}}/" + $(this).data('id') + "/edit")
            .done(setData(data));
        });
    });

My form doesn't get filled, i cannot figure why setData() doesn't function as a callback

Can somebody help me understand the difference?

Thanks for your help!!

You can make it work by pass the reference of setData instead of calling it, like:

$('button[name=btn-edit]').click(function(){
    ...
    
    $.get("{{route('categories.index')}}/" + $(this).data('id') + "/edit")
       .done(setData);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM