0

I want to get the name attribute of an imagen when someone click on it. Then, with the name, I will access a MySQL database with this name as a searching parameter for the query. But I am not able to get the name of an image from php.

Can someone help me?

This is the code that I have, I suppose to have a php function in the onclick attr.

<a class="img_a" onclick="" name="xxx">   
    <figure class="img_figure">
        <img class="img_user" src="users/xxx.png" alt="">
    </figure>
</a>

<a class="img_a" onclick="" name="yyy">   
    <figure class="img_figure">
        <img class="img_user" src="users/yyy.png" alt="">
    </figure>
</a>
2
  • are you using jquery/javascipt with php? Commented Jun 2, 2017 at 10:09
  • May be you are looking for html form to post data to php? Actually you should use javascript to access html DOM. Check this out Commented Jun 2, 2017 at 10:09

2 Answers 2

2
$(".img_a").click(function() {
  alert($(this).attr('name'));
});
Sign up to request clarification or add additional context in comments.

Comments

0

Please note that name attribute on anchor tag is obsolete some browsers may ignore this as invalid html.

rather use the .data() attribute, which stores arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

This is how your code show look :

<a class="img_a"  data-name="xxx">   
    <figure class="img_figure">
        <img class="img_user" src="users/xxx.png" alt="">
    </figure>
</a>

<a class="img_a"  data-name="yyy">   
    <figure class="img_figure">
        <img class="img_user" src="users/yyy.png" alt="">
    </figure>
</a>

<script type="text/javascript">

    $(".img_a").click(function() {
   var imgname = ($(this).data('name'));

   alert(imgname)

   //send imgname to a php file using ajax

});

working demo :

$(".img_a").click(function() {
   var imgname = ($(this).data('name'));

   alert(imgname)

   //send imgname to a php file using ajax

});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

<a class="img_a"  data-name="xxx">   
    <figure class="img_figure">
        <img class="img_user" src="users/xxx.png" alt="">
    </figure>
</a>

<a class="img_a"  data-name="yyy">   
    <figure class="img_figure">
        <img class="img_user" src="users/yyy.png" alt="">
    </figure>
</a>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.