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.
2 Answers 2
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>
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.
pdp-add-to-wishlist