Ajax jQuery Best practices: avoid inline script?? then how do I pass variables

400 views Asked by At

I just read in a best practices article for jquery and ajax that I should avoid defining behavior for elements on the page with inline script. That does make sense since it makes the code very readable.

However, I want to ask what should I do then, if I need to pass server-side variables to javascript. Like consider the following code...

<?php foreach($product as $product_id): ?>
<input type="button" value="Delete Favorite" onclick="delete_favorite('<?php echo $product_id; ?>')" />
<?php endforeach; ?>

Should I be using hidden form values for such a case? or may be adding adding the server side variable in the id of element I am defining the behavior for? like so..

<input type="button" value="Delete Favorite" id="button<?php echo $product_id; ?>" />

Any suggestions?

3

There are 3 answers

1
alex On BEST ANSWER

There are a few things you could do, one of them would be use a custom attribute such as data-product-id (data- prefix is in HTML5 spec I believe).

Though, you could also give that input an id such as product-343 and then get the id using...

$(this)[0].id.replace(/\D/g, '');

(assume this points to an input element).

3
Chandu On

Try this:

<?php foreach($product as $product_id): ?>
    <input id="fav-<?php echo $product_id; ?>" class="prod-fav" type="button" value="Delete Favorite"/>
<?php endforeach; ?>

<script type="text/javascript">
    $(function(){
        $(".prod-fav").click(function(){
                    var $this = $(this);
            var id = $(this).attr("id").replace(/[^0-9]/g, "");
            delete_favorite(id); // Call delete_favorite or
                    //delete_favorite.call($this, id); //To retain the calling element context or
                    // implement you delete function right here..
        });
    });

</script>
0
aavezel On

Use data- prefix attribute. http://jsfiddle.net/zJWfB/