onchange reload page with value of select - php

I have a table displaying results, I want to give people the ability to update the results of a cell/field individually without needing a whole update form
Here is what I have:
echo "<select name='tv_taken' id='tv_taken' onchange='window.location=\"samepage.php?update=tv_taken&update_id=$tv_id\" '>";
As you can probably tell its a select box with a list of users. Now the only problem is i need to pass the new selected value in the url string, so i want the new value of the select.
So lets say it was mary and someone chooses a new user John I want something like this
echo "<select name='tv_taken' id='tv_taken' onchange='window.location=\"samepage.php?update=tv_taken&update_id=$tv_id&user_name=$find_username\" '>";
What I'm not sure on is there a way to pass the changed value via php or will I need a javascript solution?
Ill then use an
IF if(isset($_GET['tv_id']))
{
Do the update
}
This is not a public site so I'm guessing there is a more secure way to do this but this should probably suffice since it will only be team members using it who would be required to login before they can see this page.

You'll want to use JavaScript to achieve this.
Here's a jQuery solution:
$('#tv_taken').change(function() {
window.location = "samepage.php?update=tv_taken&update_id=" + $(this).val();
});
And here's a vanilla JavaScript solution:
document.getElementById('tv_taken').onchange = function() {
window.location = "samepage.php?update=tv_taken&update_id=" + this.value;
};

window.addEventListener('load', function(){
var select = document.getElementById('tv_taken');
select.addEventListener('change', function(){
window.location = 'pagename.php?tv_id=' + this.value;
}, false);
}, false);

Related

Display Table with AJAX, select row, display row in other table, save into database

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.

Jquery code requires two individual clicks

I have some issues with JQuery.
Code;
$(document).ready(function(){
$("#area_results").click(function(){
$("#areaclickpass2 a").click(function(){
var value = $(this).html();
var input = $('#inf_custom_TESTclubarea');
input.val(value);
$("#area_results").hide(); // hide results after click
});
});
});
The current website is requiring 2 clicks to input the value into a field.
I understand why it's doing this (Best solution I can think of to achieve the outcome), however I was curious whether it is possible to achieve the same result by only using a single click.
Thanks for your time.
Create a variable that counts up with each click and execute your code when that variable equals 2.
$(document).ready(function(){
var click_count = 0;
$("#area_results").click(function(){
click_count++;
if(click_count==2){
var value = $(this).html();
var input = $('#inf_custom_TESTclubarea');
input.val(value);
$("#area_results").hide(); // hide results after click
}
});
});
You are binding a event handler within another event handler. #areaclickpass2 will not be handled unless you click on #area_results first.
Just move $('#areaclickpass2') event binding out of #area_results scope:
$("#area_results").click(function(){
//may not even be necessary to have this
});
$("#areaclickpass2 a").click(function(){
var value = $(this).html();
var input = $('#inf_custom_TESTclubarea');
input.val(value);
$("#area_results").hide(); // hide results after click
});

Php variable to JavaScript

How to add the value of php variabele to jquery variable and adds them,i have a form that will take a value and post to second page where second page contains a div panel where the form checkboxes values are adding and subtracting,basically i want to add the submitted value from page1 to page2.Here is the code.I have 3 form values which will be redirected one by one.Whenever user submits the respective button
if($_POST['submit'])
{
$beg=$_POST['basic'];
}
function refreshPrices() {
var currentTotalValue = 0;
var beg=?????
$("#results div").each(function() {
if (!isNaN(parseInt($(this).find("span").text().substring(1)))) {
currentTotalValue += parseInt($(this).find("span").text().substring(1));
}
});
$("#totalValue").text("$" + currentTotalValue)
}
var beg=<?php echo $beg; ?>
Try this:
var beg = '<?php echo $beg ;?>';
if you want to add to the total value you can do this:
currentTotalValue = currentTotalValue + parseInt(beg);
its better to do it this way :
var js_var = '<?=json_encode($php_var);?>';
This way you will be able to transfer any type of data to js (arrays, objects, strings, etc.) and access it easily like this:
js_var['element']
var beg = '<?php echo $beg ;?>';
But this can be only one once during the load of the page. After that we cant assign a server side script to js.
Retrieve value by input class or id like dat
var beg = $("#basic").val();

Getting a record row in php using javascript

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/

How do I get the values and id's of multiple select lists and pass it to AJAX?

I am trying to iterate through a number of selects in a cell of a table (they are not in a form). I have a submit button when pressed is supposed to retrieve the values and id of each select list which I will pass to the server via AJAX and PHP. My table is a table of students of a course. The table contains the students name and their attendance for a lesson in the course.
This is my table on Pastebin and jsFiddle. http://pastebin.com/NvRAbC7m and http://jsfiddle.net/4UheA/
Please note that this table is entirely dynamic. The no. of rows and the info in them is dynamically driven.
This is what I'm trying to do right now with jQuery. Please excuse the logic or the complete nonsense that is my JavaScript skills. I don't actually know what I'm doing. I'm just doing trial and error.
$('#saveAttendances').live('click', function()
{
var attendSelect = $('.attendSelect');
var students = new Array();
//get select list values and id.
for(var i in attendSelect)
{
students['student_id'] += attendSelect[i].id;
students['student_id']['attedance'] += attendSelect[i].value;
console.log(students['student_id']);
}
//after retrieving values, post them through ajax
// and update the attendances of students in PHP
$.post("",{ data: array }, function(msg)
{
alert(msg);
});
});
How do I get the values and id's of each select list and pass it to AJAX?
Edit
If you insist on going against jQuery's grain and using invalid HTML, here's a suitable solution for you:
$(function() {
$('button').click(function(){
var data = $(".attendSelect").wrap('<form/>').serialize();
$.post('process.php', data, function(response){ ... });
return false;
});
});​
Worth mentioning, this example does not rely on fanciful .on() or .live() calls. However, this requires you to have the proper name attribute set on your <select> elements as described below. This also resolves your invalid numeric id attributes issue.
See it working here on jsFiddle
Original Answer
First off, some minor changes to your HTML. You need to wrap your <select> elements in a <form> tag. Using the form tag will give you access to jQuery's .serialize() method which is the exact functionality you're looking for. Personally, I'd recommend doing things the jQuery Way™ instead of implementing your own form a serialization. Why reinvent the wheel?
Next, your td have non-unique IDs. Let's update those to use a class attribute instead of an id. E.g.,
<td class="studentName">Aaron Colman</td>
Secondly, your <select> elements could benefit from a name attribute to make form processing way easier.
<select class="attendSelect" name="students[241]">
...
<select class="attendSelect" name="students[270]">
...
<select class="attendSelect" name="students[317]">
...
Lastly, jQuery's .serialize() is going to be your winning ticket.
​$(function() {
$('form').submit(function(){
$.post('process.php', $(this).serialize(), function(response){ ... });
return false;
});
});​
Upon submit, the serialized string will look something like
students[241]=Late&students[270]=Absent&students[317]=default
See it working here on jsFiddle
live() is deprecated as of jQuery 1.7, use on() instead
http://api.jquery.com/on/
students is an array, so I don't think you can do students['student_id'], if you would like to push an array of student, you can:
$('#saveAttendances').on('click', function() {
var students = [];
// iterate through <select>'s and grab key => values
$('.attendSelect').function() {
students.push({'id':$(this).attr('id'), 'val':$(this).val()});
});
$.post('/url.php', {data: students}, function() { // do stuff });
});
in your php:
var_dump($_POST); // see what's inside :)
As #nathan mentioned in comment, avoid using number as the first character of an ID, you can use 'student_<?php echo $id ?>' instead and in your .each() loop:
students.push({'id':$(this).attr('id').replace('student_', ''), 'val':$(this).val()});
Here's jQuery that will build an object you can pass to your script:
$('button').click(function() {
var attendance = new Object;
$('select').each(function() {
attendance[$(this).attr('id')] = $(':selected', this).text();
})
});​
jsFiddle example.
This results in: {241:"Late",270:"Absent",317:"Late"}
Edit: Updated to iterate over select instead of tr.
Perhaps you want something like below,
DEMO
var $attendSelect = $('#tutorTable tbody tr select');
var students = {};
$attendSelect.each (function () { //each row corresponds to a student
students[$(this).attr('id')] = $(this).val();
});
This would give you an object like below,
students = { '241': 'Late', '270': 'Absent', '317': 'default' };
If the above is not the desired structure then modify the .each function in the code.
For ex: For a structure like below,
students = [{ '241': 'Late'}, {'270': 'Absent'}, {'317': 'default'}];
You need to change the code a little,
var students = [];
...
...
students.push({$dd.attr('id'): $dd.val()});
var $select = $('.attendSelect'),
students = [];
$('body').on('click', '#saveAttendances', function() {
$select.each(function(k, v) {
students[k] = {
student_id : $(this).attr('id'),
attedance : $(this).val()
};
});
console.log(students);
});

Categories