adjoke
adjoke

Reputation: 149

Use link found in the a tag to make an AJAX request on click

I have a table with dynamic values example below. I want to use the url in my dynamic url in my a tag with AJAX request base on what ID the user clicks on. When user clicks on ID 1 in the table below I want to pass the url in that a tag to my script in the AJAX url section. I would be thankful for any help

<table >
   <thead>
      <th data-field="status">ID</th>
      <th data-field="actions">action</th>
   </thead>
   <tbody>
      <tr>
         <td>1</td>
         <td><a id="test" href="test.php?id=1" >1</a></td>
      </tr>
      <tr>
         <td>2</td>
         <td><a id="test"  href="test.php?id=2" >2</a></td>
      </tr>
   </tbody>
</table>

<script>
    $(document).ready(function(){
        $("#test").click(function(){
            $.ajax({url: "", success: function(result){
                $("#div1").html(result);
            }});
        });
    });

</script>

Upvotes: 0

Views: 1870

Answers (2)

mplungjan
mplungjan

Reputation: 177688

  1. change ID to class - IDs need to be unique <a class="test" href="test.php?id=1">...
  2. prevent the link from being followed
  3. use load - it is simpler

Like this

$(function(){
  $(".test").click(function(e){
    e.preventDefault();
    $("#div1").load(this.href); // or if you insist: $.ajax({url: this.href,...
  });
});

PS: If the links are inserted by script, you need to delegate - here I assume the table had an ID and exists at page load

  $("#tableId").on("click",".test",function(e){

Upvotes: 2

happymacarts
happymacarts

Reputation: 2595

NOTE: You shouldn't use the same id for multiple elements on the same page. I changed your ID to use class instead I also added a preventDefault() to prevent the link from doing its normal job (unless you want to in which case remove that line)

    $(document).ready(function(){
        $(".test").click(function(e){
          theURL = $(this).attr('href');
          console.log(theURL); // can be removed just included for testing
          e.preventDefault();
            $.ajax({url: theURL, success: function(result){
                $("#div1").html(result);
            }});
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table >
   <thead>
      <th data-field="status">ID</th>
      <th data-field="actions">action</th>
   </thead>
   <tbody>
      <tr>
         <td>1</td>
         <td><a class="test" href="test.php?id=1" >1</a></td>
      </tr>
      <tr>
         <td>2</td>
         <td><a class="test"  href="test.php?id=2" >2</a></td>
      </tr>
   </tbody>
</table>

Upvotes: 2

Related Questions