Magento 2 – Fix jQuery element.click Not Working

ajaxmagento2wishlist

I have used anchor tag with some id, and want to perform ajax call on its call by using id.click() but its not working.here is my code in file view.phtml

<a id="pdp-add-to-wishlist"
   class="action pdp-towishlist"
   href="#">
    <span>
        <img class="favourite" src="image source" />
    </span>
</a>

and jquery is

<script>
require(['jquery'],function($){
    $(document).ready(function(){
        $("#pdp-add-to-wishlist").click(function(){
            alert("hello");
        })
    });
});

if using with id its not working, but when used with class it works, but i need to work with id only.

I tried using with onclick() also but stuck in code

<a id="pdp-add-to-wishlist"
   class="action pdp-towishlist"
   href="#"
   onclick="addtowishlist()">
    <span>
        <img class="favourite" src="image source />
    </span>
</a>

jquery:

<script type="text/javascript">
function addtowishlist() {
    jQuery.ajax({
        type: "POST",
        url: "<?php echo $this->getUrl('wishlist/index/add'); ?>",
        data : {product:<?php echo $productId ?>},
        success: function(data)
        {
            alert("succc");
        }
        error: function (e) {
            alert("not added");
        }
    });
}

but this has some bug which let the page to load for infinite time.

Best Answer

I don't know exactly what are you doing Try code example below may help. You should avoid use js in template if possible. Try to call it from single file

<script type="text/javascript">
//<![CDATA[
 require([
    'jquery',
    'Magento_Ui/js/modal/alert'
], function($, alert) {
   $('#id-of-element').on('click', function(event){
        alert({
           content: $(event.target).parent().val()
        })
      })
   }
 );
//]]>
</script>
Related Topic