I have a form with a table which has 5 rows and 8 columns. This table represents the available seats in a concert hall. After the submit button is clicked, a javascript function is called, which at the moment is this:
<script>
function submit_tickets(form){
var count=0;
var booked_seats=new Array();
var c = document.getElementById(form).getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox' && c[i].checked==true){
booked_seats[count]=c[i].id;
count++;
//create an array with the booked seats' ID
}
}
//alert(booked_seats.length);
} </script>
When this function is called, I want at the same time the table of the localhost database to be updated (a table which contains all the 40 seatIDs) depending on the seats that were booked.
How can I do this, can you help me?
if you'd like to i can write example in native javascript, but for now i'll try to do it using jQUery.
function submit_tickets(form){
var seats=[];
$(form).find("input:checked").each(function(){
seats.push($(this).val());//i hope you do have a value for your input tags, and if not, then push $(this).attr('id') - but highly recommend you to follow w3c
});
$.post("your/url/to/server",{seats:seats},function(data){
console.log(data);//some info from server
})
}
I believe you need to call a php file using PHP, in which the database update is done. You might consider using jquery ajax, as in http://api.jquery.com/jQuery.ajax/
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.
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();
};
i want to create array of same id or name using getElementById..
i have a "add button", when the user press this button, its generate a dropdown list(dynamic) which the value is get from mysql..
and its looks like this when the user press 3 times..
i want to create an array of this id, and store it to mysql..
this is my JS code :
var menu_paket_array = document.getElementById('menu_paket').value;
alert(menu_paket_array);
the problem is, when i try to create this array(menu_paket_array), the value in this array is just the first id (Test 1) only..
how can i fix this?
thanks...
Using the same id for more than one element is wrong. Id is to uniquely identify certain element. Using it for more elements defeats its -purpose. If you need that for i.e. CSS styling, then use class instead, which is designed just for such scenarios.
An ID must be unique on a page. You can only use it on one element.
Instead, use a CSS class or element type to iterate (here's a fiddle demonstrating this code):
function alertValues() {
var select, selects = document.getElementsByTagName('select');
var out = "";
for (var i = 0; i < selects.length; i++) {
select = selects[i];
if (select.className && select.className.match(/CLASSNAME_TO_INCLUDE/)) {
out += select.options[select.selectedIndex].value;
}
}
alert(out);
}
A better solution, of course, would be to utilize a dom library like jQuery or mootools, with which you could do something like this:
jQuery(function($) {
vals = [];
$('select.CLASSNAME').each(function() { vals.push($(this).val()); });
alert(vals.join(','));
});
document.getElementsByClassName(names);
Where names is the classname u generate for each one.
Instead of assigning each element with id='menu_paket' (for the reasons #WebnetMobile.com explained) assign class='menu_paket'.
Instead of var menu_paket_array=document.getElementById('menu_paket').value;, do
var temp_array = document.getElementsByClassName('menu_paket');
var menu_paket_array = [];
for(i in temp_array){
menu_paket_array[] = temp_array[i].value;
}
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 have a form, and there are 5 fields. The first field is an autocomplete field. I'd like to have the other 4 fields populated based on the autocomplete field selection. The docs in github ajax.autocompleter page reference setting an id and using a js function to call the id value, but this doesn't seem efficient if using multiple fields/need multiple values in addition to the ac value.
I'm using scriptaculous, and php. I have the autocompleter functioning, but am not sure on the rest of it. I'm also not clear on how to set the additional field parameters on the php end. I suppose that I could set the id="field1Val='blah'&field2Val='blah2'" then use js to parse and populate fields, but something about that just doesn't feel right.
Any idears?
this is what we use: a jquery plugin. The good thing about this one is that you can add a callback function that allow you to change the "current" behavior.
about the line 385 you have function that parses the result:
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
you can create your own function that depending on what you get (you can send a json from the server) and then execute javascript and drive the form controls.
hope help you