How do I get the value of an ID in Ajax using $ (this)?

advertisements

Here I have 4 buttons. How can I get the value of the id for each button onto the end of data: "id=" within the ajax part? Bare in mind, each id is unique as its using a numeric counter.

So for examples sake, if I clicked the third button then the id would equal 3, if I clicked the second button, the id would 2... and so on. Using $("a").attr('id') kind of works but it will grab the first <a> tag and stick with that value for which ever button you press. I also tried $(this).attr('id') but that doesn't work either.

Any suggestions?

 <?php
    $counter = 0;

        echo '
      <button><a class="test" id="'.++$counter.'">Test</a></button>
      <button><a id="'.++$counter.'">Test</a></button>
      <button><a id="'.++$counter.'">Test</a></button>
      <button><a id="'.++$counter.'">Test</a></button>
    ';

    ?>
      <script id="source" language="javascript" type="text/javascript">

      $("button").click(function ()
      {

        //-------------------------------------------------------------------------------------------
        // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
        //-------------------------------------------------------------------------------------------
        $.ajax({
          url: 'api.php',                  //the script to call to get data
          data: "id="+ $("a").attr('id'),                        //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
          dataType: 'json',                //data format
          success: function(data)          //on recieve of reply
          {
            var id = data[0];              //get id
            var vname = data[1];           //get name
            //--------------------------------------------------------------------------------------
            // 3) Update html content
            //--------------------------------------------------------------------------------------
            $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
          }
        });
      });
      </script>


$("a").attr('id') will retrieve all the anchor tags on the page and give you the first one's id.

In the context of your event handler function, this refers to the button element which was clicked.

To get the anchor tag inside the clicked button, you can use jQuery's .find method:

$(this).find('a').attr('id');

This will find any child anchor tags and return the id attribute of the first one.