0

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.

4
  • Check for DUPLICATE ids. Do view-source (ctrl+U), and search for pdp-add-to-wishlist May 9 '16 at 12:47
  • Change your id with class May 9 '16 at 12:48
  • I have checked with duplicate id, there is no duplicate id for this. i need to change class when id is clicked so i cannot use class May 9 '16 at 13:13
  • I tried with other ideas also but again its not working.. any help May 9 '16 at 13:58
1

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>
0

I found one solution which is working, used reference site as https://stackoverflow.com/questions/8639658/jquery-add-class-to-elements-child

<span class="pdp_product_to_wishlist">
    <a id="a_product_pdp_wish_id"
       href="#">
    <span>
        <img class="favourite" src="image source" />
    </span>
    </a>
</span>

in js i have written

$(".pdp_product_to_wishlist").find('#a_product_pdp_wish_id').removeClass('favourite active');
$(".pdp_product_to_wishlist").find('#a_product_pdp_wish_id').addClass('favourite active');

which has resolved my problem, I just tried other options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.