简体   繁体   中英

how to get an id of an element, which is returned from php code

I am trying to build a db driven web site in which the user selects from a drop down menu a value and some Information from a database are returned. I use an ajax post cause i dont want the page to get refreshed:

$("#button").click(function(){ 
   var datastr = ($('#act').val());
   var datastr1 = ($('#loc').val());

   $.ajax({
      type:'POST',
      url:'activities_code.php',
      data: {datastr:datastr, datastr1:datastr1},
      success:function(response){
                $("#msg").html(response);                       
            } });});  

In the url parameter I have the following php file (this is a part of the php file):

 $query = "SELECT PK,title,Information from activities where Activities='$category'";
    $result = mysqli_query($dbcon, $query) or die('no available data');

    echo "<table>";
$num_results = 0;
$t = 0; //title counter for the id of each title
while ($row=mysqli_fetch_array($result, MYSQLI_ASSOC)) {
     // Here the columns of title and information are printed
     echo "<tr><td>";
     echo "<a href='test.php'  id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>"; 
     echo "<br>";
     echo  $x = $row['PK'];
     echo "</td></tr>";


     echo "<tr><td>";
     echo $row['Information'];
     echo "</td></tr>";
// Here I sum up the number of the results
     $num_results=$num_results+1;   
     $t = $t+1;      
 }

}

As you can see, I have a while loop in which I echo each time a link with an id:

"<a href='test.php'  id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";

What I want to do is to use this id of each link later in my code by doing something like this:

  document.getElementById("t1").value

My question is, how can I return this id's to the client side? I think I should write something in the success function but I have no idea what. If you dont understand some part of the code or I didn't explain everything clear, please ask me. Thanks D.

This is what I get when I alert(response) in the success function.

<!DOCTYPE HTML>




       <table id="container"><tr><td><a href='test.php' id="t0" target="_new"   class='pickanchor'>Rafting in Voidomatis</a><br>1</td></tr><tr><td>
      <img src="m.jpg" class="textwrap" height="120px" width="120px">
      <p style="text-align:left;">Our experienced rafting instructors will show you the best way to enjoy Voidomatis, the river with the most clear waters inSouth Europe. You can also cross the Vikos Gorge by following Voidomatis river in an attractive one and a half hour   long walk. Alternatively you can ask for the more demanding Aoos river rafting.</p>
     <br>
     <br>
     <hr></td></tr><tr><td><a href='test.php' id="t1" target="_new" class='pickanchor'>Rafting   in Lousios</a><br>4</td></tr><tr><td><img src="raf.jpg" class="textwrap" height="120" width="120">
     <p>You will be surprised to know that Greece hides numerous, densely vegetated rivers offering amazing rafting opportunities. In the whole mainland, there is a company base awaiting you, for an amazing � off the beaten track experience!</p>
     <br>
     <br>
     <br>
     <hr></td></tr><div id="r2" align="center" id="result_2">2 results for rafting were found!        
     </div></table>  <!-- End of PHP code-->

In line you presentd you made mistake. In wrong place you have added ".

echo "<a href='test.php'  id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";

It should be

echo "<a href='test.php'  id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";

As simplest solution you could add after the while loop

echo "<script> my_max_id_num=$t </script>"

This will give you knowledge about which ids are present on page. This should give your js script access to my_max_id_num variable. It's not considered best programming practice but is simple.

Second (better) way of solving problem could be returning json instead of html and rewriting your success method. This will be more work to be done:

  1. Rewrite while loop so it returns something like:

    { "data":[
    ...
    { "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
    { "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
    ...
    ]}

  2. Rewrite your ajax query so it will accept json, and rewrite success method so it will create your links on basis off data returned from server.

This way you will have both, ids and your links in one query. What's more in case of changing requirements it will be easier.

First, There is problem with ID of your anchor tag. here is correction

"<a href='test.php'  id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";

Second, Give id to your table like

<table id="container">

Third, give class to your anchor tag.

"<a href='test.php' class='pickanchor'  id=\"t.$t\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";

Now write following code into your success handle after .html() statement

NEW EDIT

$("a.pickanchor").each(function(i){

   alert(this.id);
});

The simplest solution would be to give your elements a class , that way you don't need to select based on the elements id , but you can access it easily:

eg.

<a href="#" id="t0" class="className">test 0</a>
<a href="#" id="t1" class="className">test 1</a>

$('#msg').on('click', '.className', function() {
  console.log(this.id);
});

I don't have enough rep points to ask for clarification, but what do you mean by 'return this id's to the client side'? Also what would the 'value' of the element 't1' be?

Lets say you wanted to get the link location it could be something like:

var value = $('#addButton').attr('href');

and then do something with the value (not sure what you mean by 'return this id's to the client side') but perhaps you want the value then to be visible to the client?

So if you have a div somewhere on the page where you want it to show you could populate it with you value, maybe something like:

HTML <div id="valueBox"></div>

jQuery

$("#valueBox").html(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM