Search code examples
javascriptajaxsnackjs

Posting (AJAX) data to another page


I am trying out a small JavaScript library, SnackJS and am doing pretty well. But I've hit a wall, and can't seem to figure this one out:

Snack:

<script type="text/javascript">
    snack.ready(function () {
        var parameters = {
            node: document.body,
            event: 'change',
            delegate: function (node) {
                return node.getElementsByClassName("qty")
            }
        }

        snack.listener(parameters, postToOtherPage);

        function postToOtherPage() {
            var options = {
                method: 'post',
                url: '/InlineEditing',
                data: {
                    qty: 5,
                    id: "hi"
                }
            }
        }
    });
</script>

My question is, on the change event of an input element, how do I post the id of the element, along with that element's value (qty) to another page?

I did look through the documentation, but I can't quite figure it out.


Solution

  • You're missing a

    snack.request(options, callback);
    

    call. A part from that, your code looks fine.. what's wrong with it?

    Update

    oh, I see you're not retrieving the id from the element.. from the docs: the first argument to event callback is the node which fired the event, so:

    snack.ready(function () {
        var parameters = {
            node: document.body,
            event: 'change',
            delegate: function (node) {
                return node.getElementsByClassName("qty")
            }
        }
    
        snack.listener(parameters, postToOtherPage);
    
        function postToOtherPage(event) {
            var options = {
                method: 'post',
                url: '/InlineEditing',
                data: {
                    qty: 5,
                    id: this.id
                }
            }
            snack.request(options, function(){
              // do something with response..
            });
        }
    });
    

    should work fine..

    Update

    Nope, sorry, further reading the docs I found out they're using callback.apply(this, [event]), as usual.. updated code above.

    By the way, I don't see the point in using this kind of micro-libraries instead of well-established libraries such as jQuery/Zepto, since the pros of the micro-libaries in terms of size are not worth IMO the disadvantages.

    Consider that "larger" libaries:

    • have a lot more features: what about the day you'll decide to extend your application functionality more?
    • have a larger community/commercial-based support: books, reference, guides, ...
    • are more likely to have already solved problems/issues that are still there in micro libraries. Just think of the hundreds of cross-browser compatibility hacks...

    However, this one is just my opinion, just take it as my personal advice.