DaithiOK
DaithiOK

Reputation: 135

How to pass the value from a dynamically created table into a new database query using JQuery?

So far I've created a table from a database query using the input from a dropdown menu. Now I want the user to be able to click on a cell in that table and using the the value of that cell query the database again for further information. Here's what I have:

echo "
<tr>
<td>".$value['Time']."</td>
<td><a href='#'><div value=".$value['First_Name'].">".$value['First_Name']."</div></a></td>
...

This continues on for the rest of the information but thats the code for my initial table. The user should then click on First_Name for further information provided by an AJAX request. My jQuery so far looks like this...I haven't even been able to start the AJAX as I can't pass in the value of the table cell.

$(document).ready(function(){
    $('#tables').on('click','td', function(){
            var module= $(this).val();
            alert(module);
        })

Once I figure out how to pass this value then I can move ahead with the database query but this is holding me back. Do I even need to do this if Im using JQuery AJAX? Any help is appreciated.

Upvotes: 0

Views: 91

Answers (2)

Alok Patel
Alok Patel

Reputation: 8022

It would be better to bind click event on <a> instead of <td>. That will work good too.

Now question is you want to pass some value through AJAX to PHP script. Good practice to do this is by setting data-* attributes to <a> element.

So your HTML/PHP code will look something like this,

<td>".$value['Time']."</td>
<td><a href='#' class='myLink' data-modelvalue='".$value['First_Name']."'><div value=".$value['First_Name'].">".$value['First_Name']."</div></a></td>

In above code we've given a class to <a> to bind click event on each element having this class. (Useful for multiple records generated using loop), we have also set data-modelvalue attribute to <a>.

Now update your jQuery code like this,

$('#tables').on('click','.myLink', function(e){
     e.preventDefault();
     var module= $(this).data('modelvalue');
     alert(module);
});

In above code we have bind click event on myLink class elements. Also we're fetching data-modelvalue using .data() jQuery method.

e.preventDefault() forces default action of the event to not be triggered, in our case page won't get refreshed(which is default action of any hyperlink).

References:

https://developer.mozilla.org/en/docs/Web/Guide/HTML/Using_data_attributes
https://api.jquery.com/data/
https://api.jquery.com/event.preventdefault/

Upvotes: 0

Eka Juliantara
Eka Juliantara

Reputation: 41

if you want get the text inside the element tag. Please use .text() not .val() example:

var module= $(this).text();

I hope this usefull :)

Upvotes: 1

Related Questions