Transferring a contents of a table cell into document loaded by jQuery - php

I currently have a table in the current format:
ID Client Info Case Detail Accident Date Case Opened No Days Function
-- ----------- ----------- ------------- ----------- ------- --------
which contains dynamic information being pulled out of the database.
The ID column is of particular importance because I need to extract the data from this cell when the user clicks on the "Manage" button under the function column.
Right now this is the code that runs when the user clicks on the "Manage" button.
<script>
$(document).ready(function () {
$(".manage").click(function () {
$('#casesHeading').hide("slow");
$('#casesTable').hide("slow");
$('#results').load('components/manage.php');
});
});
</script>
A heading and table is hidden and the page "manage.php" is loaded in results div.
But I was just wondering if there was anyway for me to transfer the content of the ID cell (this varies per row) obviously into the manage.php file (which is currently empty).
So if the user clicks on a row with the ID cell data 233-cv then this information would be transferred over into the manage.php file. Hopefully I'm making sense. I read up on the jQuery .find function and it made some sense but I have no idea how to incorporate it in this instance.
UPDATE 1
I'm trying to accomplish somethng similar to this http://jsfiddle.net/ZjvAz/.
UPDATE 2
I've tried the following code but it doesn't seem to be working.
<script>
$(document).ready(function () {
$(".manage").click(function() {
var clickedButton = $(this);
clickedButton.parent().find(".result").text(
clickedButton.parent().parent().parent().find('.caseID').text()
);
});
});
</script>

I would have my manage.php file take the case ID as an argument. It would be called in a manner such as manage.php?caseId=123.
If you have control over the generated data, you could generate the required information to go in the button. There is no need for jquery code to traverse the DOM to the ID field. I would just generate something like this in the table source
<tr>
<td class="id">123</td>
...
<td class="function">
<button class="manage" onclick="loadManagementPage(123)">manage</button>
</td>
</tr>
If you cannot control the HTML source and do need to navigate, your best friend is probably using closest() which navigates up the dom. Use this to find the row element tr
For self-documenting purposes, i am not using chaining here
$( '.manage' ).click(function(){
// find the row we are in
var $self = $( this );
var $row = $self.closest( 'tr' );
// read the id
var $idCell = $row.find( 'td.id' );
var caseId = $idCell.text();
// locate an area on the page and dynamically load in some content
var $target = $row.find( 'td.result' ); // find the result cell
var $target = $( '#knownId' ) // *OR* find a div with a known id
$target.load( 'manage.php?caseId=' + caseId );
});

jQuery.load( handler(eventObject) ) Returns: jQuery
Description: Bind an event handler to the "load" JavaScript event.
As 'components/manage.php' isn't an event-handler – what are you trying to do?
If you want to request data from the server (also with sending smoe ID to it), you should read about the jQuery.ajax( url [, settings] ) function.
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/load-event/

Related

Updating AJAX request variable with ID of PHP generated table row on click

Im probably overlooking something very obvious but at this point i surrender and need help.
Here is my situation. When my page loads, in a while loops, PHP generates a table with data from my server. Each table row has a name column, phone, etc. One of the columns is an icon that when clicked allows the user to view a popup with notes on this particular lead. Easy stuff.
The icons in each row have the same class name and their ID's are unique.
I have an AJAX request that should be pulling the notes data from the server and displaying it in the popup when the user clicks on the relative icon. I am trying to use $('.class').click(this).attr('id'); to set a variable in my AJAX request with the id that needs to be submitted to my PHP script.
PROBLEM: The AJAX request and return seems to be working fine but no matter which row icon I click on it only displays the data that belongs to the first row, or the first instance with the class name 'homelead' Example: I click on row 1 icon and i get a popup with row 1's notes, GREAT!. I click on any other row and it only shows the 1st rows data, :(. I have confirmed that the ID's associated with each row icon are correct by doing a simple click.(this).(id) and alerting the id belonging to the row icon. All is correct, just can't seem to get the JS variable to update with the correct ID.
Im confused why this is. Any help would be appreciated. Here is my current code.
HTML:
<td>
<img class="homelead" id="<?php echo $leadsfetch['unit_id'];?>"
onclick="ajax_unitnotes();" src="images/list-view.png">
</td>
<?php echo "</tr>"; } ?>
AJAX request:
function ajax_unitnotes(){
var hr = new XMLHttpRequest();
var url = "PHP/getnotes.php";
// this variable should update with clicked rows id before submitting to PHP script
var unitidnotes = $('.homelead').click(this).attr('id');
var vars = "unitidnotes="+unitidnotes;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("unitnotes").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("unitnotes").innerHTML = "processing...";
}
As you are using an onclick trigger in the tag itself - which is usually un common when using jQuery. You can do this:
<img class="homelead" id="<?php echo $leadsfetch['unit_id'];?>"
onclick="ajax_unitnotes($(this));" src="images/list-view.png">
And the in your function
function ajax_unitnotes(e){
var unitidnotes = e.attr('id');
}
Your current code
var unitidnotes = $('.homelead').click(this).attr('id');
Actually does not know what it the this object you are trying to access.
Better yet you can use a jQuery event, remove the onclick from the img tag and have an event like this:
$('.homelead').click(function(){
id = $(this).attr('id');
});
You could pass the clicked object this to the function trigged by "onclick":
onclick="ajax_unitnotes(this);"
That will make the DOM object you clicked on available inside the JS function.
You need to change the function signature accordingly:
function ajax_unitnotes(clickedElement){
and then you can alter this
var unitidnotes = $('.homelead').click(this).attr('id');
to
var unitidnotes = clickedElement.id;
This will give you the value of $leadsfetch['unit_id'] = img id.

Passing a variable from within a while loop to a jquery

I have a web page that lists a number of companies from a MYSQL database, the listing just shows the name of the company. When user clicks on the company name a jquery accordion slider shows the rest of the information about that company.
When company name is clicked it also sends a request to a php script to log that a person has viewed that company's details.
My Problem
I want to send the ID for each record to the php script.
I have achieved this by including the accordion jquery code within the while loop that reads the output of the mysql query, but it generates a lot of unnecessary source code (i.e. for each company listed).
I need to include the jquery accordion code outside of the while statement.
How do I pass the id of each database record (i.e. company name) to the $.post in the jquery code, when it is outside of the while loop?
Accordion Jquery code
$(document).ready(function() { $('div.listing> div').hide(); $('div.listing> h4').click(function() {
$.post("/record.php", { id: "<?php echo $LM_row02[id]; ?>" } )
var $nextDiv = $(this).next();
var $visibleSiblings = $nextDiv.siblings('div:visible');
if ($visibleSiblings.length ) {
$visibleSiblings.slideUp('fast', function() {
$nextDiv.slideToggle('fast');
});
} else {
$nextDiv.slideToggle('fast');
} }); });
Any idea most welcome.
When you create the HTML (I assume you do that in the loop as well), add a data-* attribute with the ID as value to the element and read that value with jQuery when the element is clicked on.
E.g. your resulting HTML will look like:
<h4 data-id="123">Some title</h4>
and your JavaScript:
$('div.listing > h4').click(function() {
$.post("/record.php", { id: $(this).attr('data-id') }, function() {
// ...
});
});
When you create the h4 element in html add a html5 data attribute like
<h4 data-companyid="<?php echo $LM_row02[id]; ?>">Company Name</h4>
Then use that companyid in your ajax call like
$.post("/record.php", { id: $(this).data('companyid') } );

Count clicks on one button, save it to MYSQL and then display the current value (AJAX, PHP)

Here is what I want to accomplish on http://geheimprojekt.nomachines.org/
User clicks on "Nochmal!" Button (New word combination is generated)
Send the click to my MySQL database (withou reloading the page), increase "clicked" row by 1
Update the text in a paragraph "n Word combinations have been generated so far."
This is my first attempt to work with AJAX.
I have jQuery knowledge but i can't connect the dots it seems.
The SQL
CREATE TABLE IF NOT EXISTS `sggcount` (
`counter` bigint(20) NOT NULL DEFAULT '2'
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_german2_ci;
--
-- Dumping data for table `sggcount`
--
INSERT INTO `sggcount` (`counter`) VALUES
(2);
To get this to work is very simple. You need some html for the future div where you want to place the couting:
<div id="counting"></counting>
Then right at the end of the generator() function you add this:
function generator(){
/*your code here...*/
var element = document.createElement("div");
element.setAttribute("id", "result");
element.appendChild(document.createTextNode(name));
document.getElementById("placeholder").appendChild(element);
/*the ajax code here*/
var url='urltophpfile/phpfile.php';
$.get(url,function(data){
$('#counting').html(data+' Word combinations have been generated so far.');
});
}
Now in your phpfile.php file you will need the code to increment the count. I guess you know how to do this part if now i can help with it too. I'll add some sample code here so you have an idea.
<?php
mysql_connect('localhost', 'db-sgg', 'password') or die('Cannot connect to database server');
mysql_select_db('db1152127-sgg') or die('Cannot select database');
$databasecall = mysql_query("SELECT counter FROM sggcount WHERE counter > 1");
/*so here you select the already stored value and then you make an update to increment it*/
mysql_query("UPDATE sggcount SET counter=counter+1");
$count = mysql_fetch_assoc($databasecall);
echo $count['counter']+1;
?>
By doing the echo above you will return the incremented value and the ajax will display it.
Update 1
Added more comprehensive php code
NOTE: if you add the jquery script please change the generator function to use jquery.
Using jQuery you could bind click event to your button and make ajax request.
JQuery ajax doc
On server side your PHP page should update SQL data.
Follow Javascript demo code
$(document).ready(function(){
$('button-selector').click(function(){
//use jquery ajax call to call php server page that update SQL data
$.ajax({
url: "updateClick.php",
context: document.body
}).success(function() {
//success callback
});
});
});
to send AJAX request on clicking use:
$('#button').click(function(){ // when user `click` element with `id="button"` (#button)
$.ajax({ // Start AJAX call
url: 'accept.php', // URL to send AJAX request
success: function(data) { // Function to execute on SUCCESS reply (reply data as paramenter)
var cc = $('#clicks_count').html(); // In your element with `id="clicks_count"` you store your click count (`<a id="clicks_count">21</a>`). Assign to `cc` javascript variable value of clicls_count
$('#clicks_count').html(cc + 1); // Increasing clicls_count on 1 and write it to `<a id="clicks_count">22</a>`
}
});
});
At accept.php use script increasing clicks counter by 1.

How to get ID value with jquery and send to PHP script?

I am trying to get an id value of a link with jquery then send that id to a php script (in this case sending it to a php sql query).
I have a link like this on the main page:
Category One
when this link is clicked, I would like jquery to grab the id value ('category1') and place it in a seperate php file that holds my db queries.
in other words the id value would be inserted into the query below once the link is clicked so I don't have to manually enter in the category part of the query:
SELECT * FROM maindb WHERE category="category1"
Any help on this would be great, thanks.
<a class='foo' id='category1'>Category One</a>
<a class='foo' id='category2'>Category Two</a>
<a class='foo' id='category3'>Category Three</a>
<script>
$(document).ready(function() {
$('.foo').click(function() {
// You might do:
window.location='somefile.php?id=' + this.id;
// or pass it as an argument to
$.getJSON('somefile', {id: this.id}, function(result) { alert('Success') });
});
});
</script>

Printing results from function on page onclick?

Honestly, I'm not even sure the best way to go about this, but essentially, I have a function in an include file that takes a $type parameter and then will retrieve/print results from my db based on the $type passed into it... What I'm trying to do is have a series of links on a page that, when you click on a certain link, will run the function and display the results accordingly...
So, on the initial load of the page, there is a table that displays everything (and I'm simplifying the table greatly...)
<table>
<tr><th>Item</th><th>Type</th></tr>
<tr><td>Milk</td><td>Dairy</td></tr>
<tr><td>Yogurt</td><td>Dairy</td></tr>
<tr><td>Chicken</td><td>Meat</td></tr>
<tr><td>Zucchini</td><td>Vegetable</td></tr>
<tr><td>Cucumber</td><td>Vegetable</td></tr>
</table>
And, then, in a sidebar, I have a series of links:
Dairy
Meat
Vegetable
I'd like to filter the initial table (and back and forth, etc.) based on the link that is clicked, so that if the user clicks "Vegetable", the function from my include file will run and filter the table to show only "Vegetable" types...
The first idea that comes to mind is to add a class attribute to the <tr> tags and id attribs to the <a> tags so that you can easily filter that way:
<tr class="dairy"><td>Milk</td><td>Dairy</td></tr>
<tr class="meat"><td>Chicken</td><td>Meat</td></tr>
Dairy
Meat
Then in your JavaScript (I'm using jQuery here):
$('a').click(function(evt){
var myId = $(this).attr('id');
$('tr').each(function(idx, el){
if ($(el).hasClass(myId))
{
$(el).show();
}
else
{
$(el).hide();
}
});
});
This has the added benefit of allowing you to localize the text without having to change your code.
Ok I created a proper answer. You can do it the way Darrel proposed it. This is just an extension for the paging thing to avoid cookies:
$('a').click(function(evt){
var myId = $(this).attr('id');
// append a idndicator to the current url
var location = "" + document.location + "";
location = location.split('#',1);
document.location = location + '#' + $(this).attr('id');
//append to next and previous links
$('#nextlink').attr({
'href': $('#nextlink').attr('href') + '#' + $(this).attr('id')
});
$('#previouslink').attr({
'href': $('#previouslink').attr('href') + '#' + $(this).attr('id')
});
$('tr').each(function(idx, el){
if ($(el).hasClass(myId))
{
$(el).show();
}
else
{
$(el).hide();
}
});
});
Some code that is executed after page load:
var filter = window.location.hash ? '[id=' + window.location.hash.substring(1, window.location.hash.length) + ']' : false;
if(filter)
$('a').filter(filter).click();
This simulates/executes a click on page load on the link with the specific id.
But in general, if you have a large database, you should filter it directly with SQL in the backend. This would make the displayed table more consistent. For example if page 1 may only have 3 rows of class 'dairy' and on page 2 10 of class 'dairy'.
If youre printing out the whole tabel up front there is no need to go back to the server you can simple hide all teh rows of a given type. For example with jQuery:
$('#sidebar a').click(function(){
// grab the text content of the a tag conver to lowercase
var type = $(this).text().toLowerCase();
/* filter all the td's in the table looking for our specified type then hid the
* row that they are in
*/
$('#my_data_table td').contents().filter(function(){
return this.nodeType == 3 && this.toLowerCase() == type;
}).parent('tr').hide();
return false;
});
Really though the suggestion abotu adding a class to the TR is better because filtering on text content can get tricky if there is content youre not expecting for some reason (hence my conversion to all lower case to help with this).

Categories