i would like some guidance as to how to handle things after an ajax call.
I have a table with values showing numbers, those numbers are totals of other values. SQL statements wise, everything works.
But I don't really understand how am I supposed to refresh that table when I click on buttons.
These buttons are supposed to show the same table structure with different values, from another SQL query.
Here is what I have at the moment.
JS/AJAX
$(document).ready(function () {
var currentID;
$('.member_list li a').click(function() {
currentID = $(this).attr('data-key-value');
$.ajax({
type: "POST",
url: "index_report.php",
data: { ID : currentID }
}).done(function(response) {
var table = $('.manage_table').DataTable();
table.remove().draw();
});
});
});
sample of buttons that should be pressed to get the new values:
<li>Henry</li>
<li>Joe</li>
<li>Hector</li>
and the line that launch the DB call for the individual data.
$temp_data_1 = $className>select_number_by_person($date_begin_month[$i],$date_end_month[$i], $_POST['ID']);
I figured out my problem was due to DataTable.
EDIT: Apparently, I can't use it with templates.
I am currently using smarty, and all my table is auto generated with loops.
For some reason, DataTable is only giving me Errors.
Any Idea how to do it without DataTable?
I am probably missing a huge chunk of code for this to work.
Thanks in advance of any advice.
I can see that you're using DataTable couldn't you do something like this?
var currentID;
$('.member_list li a').click(function() {
currentID = $(this).attr('data-key-value');
dataTableUpdate();
});
function dataTableUpdate(id){
var query = $.param({ID : currentID})
var source = "index_report.php?" + query
// Get API instance
var table = $('.manage_table').DataTable();
// Load data using API instance
table.ajax.url(source).load();
};
Related
I have been given very specific instructions on how to do a certain feature.
On the website Im working on you can create events and edit those. Those events can have guests, which are different from normal members that attend an event.
Every guest has to be invited by a member. So I have a table displaying members and in that very Table I have a picture. When you click on said picture it will display a list of guests, that arent part of the event yet.
All of this already works, but now comes the part that I am unable to do.
Now the admin needs to be able to select a guest. After a row is clicked it must be taken out of the table and displayed in a seperate HTML Table, in case multiple guests can be chosen.
After that the admin needs to press a submit button, to invite the guest to the event.
Now my explicit questions are:
How can I make my row selectable? I found this but I get the error TypeError: $(...).selectable is not a function if I try to use it. Edit: I have also since found this. When I use this I dont have any errors in my console, but it still does not work. Could it be that it doesnt recognize my table?
How can I display the row in a seperate HTML Table? With $("#row").click(function() maybe?
I tried doing enough research, to warrant asking such a specific question, so please refrain from saying "just google it". Instead I would be thankful for linking me to the right source! I dont want somebody to do it for me, Id just be thankful for any help! :) I am still very new to jQuery and AJAX.
Here is my jQuery for displaying the table, for context:
$(document).ready(function(){
$("#show_guests").click(function(){
event.preventDefault();
$.ajax({
url: '/widenmoos/administrator/components/com_memberportal/anlassansicht/Gast_Liste.php',
success: function(data,status)
{
createTableByForLoop(data);
},
async: true,
dataType: 'json'
});
});
});
function createTableByForLoop(data)
{
var eTable='<table id="Selectable_Guest_Table"><tr><th>Guest</th>'
for(var i=0; i<data.length;i++)
{
eTable += "<tr>";
eTable += "<td>"+data[i][0]+ " " +data[i][1] + ", " +data[i][2]+"</td>";
eTable += "</tr>";
}
eTable +="</table>";
$('#forTable').html(eTable);
}
Try with the following code:
I'm dynamically creating a new table to contain the selected guests. You can then use the same way I'm storing each rows' guest attributes to move parameters and use them whenever you need to send the emails.
function createTableByForLoop(data)
{
var eTable= $("<table />").attr("id","Selectable_Guest_Table").append(
$("<tr />").append(
$("<th />").html("Guest")
)
);
for(var i=0; i<data.length;i++)
{
eTable.append(
// you can store whatever data comes from the js object in this way:
// (in case you can stringify the entire object and store it as row attribute)
$("<tr />").attr("data0",data[i][0]).attr("data1",data[i][1]).attr("data2",data[i][2]).append(
$("<td />").html(data[i][0]+ " " +data[i][1] + ", " +data[i][2])
).click(function()
{
var data0 = $(this).attr("data0");
var data1 = $(this).attr("data1");
var data2 = $(this).attr("data2");
$("#selected_guests").append(
$("<tr />").append(
$("<td />").html(data0+" "+data1+" "+data2)
)
);
// Remove row from original table
$(this).remove();
})
);
}
var selectedGuestsTable = $("<table />").attr("id","selected_guests").append(
$("<tr />").append(
$("<th />").html("Selected Guest")
)
);
$('#forTable').append(
eTable,
selectedGuestsTable
);
}
The best way, by the way, is to pass only the guest id on both tables rows, referring then the entire object from the data array when needed.
Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/
I want to do an update statement in my database, after an element gets dropped on a jQuery UI droppable element.
$("#pictures th div").droppable({drop: function(ev, ui) {
alert('You filled this box with a picture');
var this_id = $(ui.draggable).attr("alt");
var draggableId = ui.draggable.attr("id");
}
I know how to get the information (see the code above) I need, but how can I put them now into the database ?
Thank you !
At this point, you can use jQuery's $.post() method to post to a PHP file you've written. In the $.post(), you can pass the ids you would like to have written to your database.
So something like this:
$.post("/save.php", { imageId: this_id, draggedId: draggableId }, function (data) {
alert("success!");
});
Post the variable values to other page lyk this:
$.ajax({
type: "POST",
url: "data.php",
data: "Cat=" + id + "&Wid=" + WID
});
and then on data.php page get the values lyk this:
$Cat=$_POST['Cat'];
$WID=$_POST['Wid'];
simply store them in database by using insert query,hope it will help you.
Basically i have php code which retrieves data from a database into a table, i have placed a button with an onclick function in each row of the table. the buttons aren't working cause its php(server side).
Could someone point me in the right direction to do this? retrieve data from Db put into a table with a button in each row with an onclick event.
thanks
Just use an anchor in each row and assign a class name for example :
<a class="delete_btn" href="index.php?action=fetchdta&id=1">Delete</a>
then use this jquery code on top of your page in a script tag :
<script>
jQuery(document).ready(function ($) {
$('.delete_btn').click(function(){
var urlt = $(this).attr('href');
$.ajax({
url: urlt,
success: function(data) {
//do Everything you want
}
});
return false;
});
</script>
Hi everyone I have been working on this particular problem for ages by now,plz help.
I have looked at jQuery: Refresh div after another jquery action?
and it does exactly what I want but only once! I have a table generated from db and when I click on delete it deletes the row and refreshes the div but after which none of my jquery functions will work.
$('#docs td.delete').click(function() {
$("#docs tr.itemDetail").hide();
var i = $(this).parent().attr('id');
$.ajax({
url: "<?php echo site_url('kt_docs/deleteDoc'); ?>",
type: 'POST',
data: 'id=' + i,
success: function(data) {
$("#docs tr.itemDetail").hide();
$("#f1").html(data); // wont work twice
//$("#docs").load(location.href+" #docs>*"); //works once as well
}
});
});
in my body I have
<fieldset class='step' id='f1'>
<?php $this->load->view('profile/docs_table'); ?>
</fieldset>
profile/docs reads data from db. <table id='docs'>....</table>
and my controller:
function deleteDoc() {
$id = $_POST['id'];
$this->load->model('documents_model');
$del = $this->documents_model->deleteDocument($id);
return $this->load->view('docs_table');
}
Thanks in advance!
Are you removing any expressions matching $('#docs td.delete') anywhere? If so, consider using $.live(), which will attach your function to ALL matching elements regardless of current or in the future; e.g.
$('#docs td.delete').live('click', function() {
// Do stuff.
});
http://api.jquery.com/live/
Try using bind() instead of click(). The click() method won't work on dynamically added elements to the DOM, which is probably why it only works the first time and not after you re-populate it with your updated content.
You should just have to replace
$('#docs td.delete').click(function() {
with
$('#docs td.delete').bind('click', function() {
Are you replacing the html elements that have the events on them with the data your getting through ajax? If you end up replacing the td.delete elements, then the new ones won't automatically get the binding.