Ajax Question

How to pick id of images dynamically on click

Hy!
I am calling images from database in a div. By clicking on any image, i am displaying a same modal having product details.

For displaying modal, in JavaScript, i am receiving the images by src, that was clicked and hence opening same modal.
Now i want to get the id of each image that is clicked for using that id in php script.
How can i do that?

php

<div data-toggle='modal' data-target='#myModal'>

<h3 align='center'>$product_name</h3>
<center>
<img src='admin_area/product_images/u_buyer_product_img/$product_image1' class='getSrc' />
<br></center>
</div>


javascript

<script>
$(document).ready(function(){
$('.getSrc').click(function() {
var src =$(this).attr('src');

$('.showPic').attr('src') = src;
});

});
</script>


html

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">

<!-- Modal content-->
<div class="modal-content">
<img src="" class="showPic">
<div class="modal-header" style="padding:35px 50px;">
<button type="button" class="close" data-dismiss="modal">&times;</button>

<h3 align="left">Product Name
</h3>
<p>Product Discription</p>

</div>
<div class="modal-body" style="padding:40px 50px;">
<div>
<label> Product-Code :- </label>
</div>
<div>
<label> Quantity :- </label>
</div>
<div>
<label> Price :- </label>
</div>
<div>
<label> Action :- </label>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
</div>

</div>
</div>
</div>

Answer

Given that in the PHP script you have and $id variable containing the ID of the image being displayed:

<div  data-toggle='modal' data-target='#myModal'>
  <h3 align='center'>$product_name</h3>
  <center>
    <img src='admin_area/product_images/u_buyer_product_img/$product_image1' class='getSrc' data-image-id='$id' /> 
    <br>
  </center>
</div>

Then in JS you can retrieve the id:

<script>
$(document).ready(function(){
$('.getSrc').click(function() {
        var src =$(this).attr('src');
        var id = $(this).data('image-id');
        $('.showPic').attr('src') = src;
     });
});
</script>
Comments