Making table cells clickable - php

I currently have a table of about 30 rows and I would like to make <td> clickable in each case:
<tr height="100px" align="center">
<?php do { ?>
<td style="background-color: <?php echo $row_dd1['colour']; ?>;">
<form action="pay.php?id=<?php echo $row_dd1['dNo']; ?>&user=<?php echo $username; ?>" method="post">
<input type="hidden" id="<?php echo $row_dd1['dNo']; ?>"><input type="hidden" value="<?php echo $username; ?>">
<button type="submit" class="link" id="t<?php echo $row_dd1['dNo']; ?>"><span><?php echo $row_dd1['dNo']; ?></span></button></form>
</td>
<?php } while ($row_dd1 = mysql_fetch_assoc($dd1)); ?>
</tr>
How do you make the table cell clickable? I would like it to have the same link as the form action that I have used which is:
<form action="pay.php?id=<?php echo $row_dd1['dNo']; ?>&user=<?php echo $username; ?>" method="post">

This is a perfect example of where to use .delegate(), like this:
$("#myTableID").delegate("td", "click", function() {
$(this).find("form").submit();
});
.delegate() attaches one handler to the <table>, rather than n handlers, one per cell. If you just want to navigate to the URL, it would look like:
$("#myTableID").delegate("td", "click", function() {
window.location.href = $(this).find("form").attr("action");
});

To actually submit the form:
$('td > form').each(function(i,e){
var form = $(this);
var cell = form.parent();
if(cell.is('td')){
cell.click(function(){
form.submit();
});
}
});
If you jsut want to follow the link instead, jsut modify the form.submit() part to change window.location.href with form.attr('action').

What about jQuery's click-event?
$('td').click(function () {
$('form', this).submit();
return false;
});
This submits the form inside the clicked <td>.

Related

Jquery only fired when changing one select input but not the other select tags

for a users table, I'm trying to dynamically create a feature which allows the admin person to change the user's role from the table by clicking the select tag and changing the the role from the list of the roles provided which would fire the JQuery at the bottom with an AJAX called. The problem is, it is only responding to just one select tag on the table which is the one at the top row. I have someone understanding of what is wrong but have no idea how to resolve it. I think I need to loop through the events and listen to which is firing but I do not know how to implement that. Any help is much appreciated.
<tbody>
<?php while ($all_admins = mysqli_fetch_assoc($admins)) { ?>
<tr>
<td><img src="<?php echo url_for('../images/staff/'.$all_admins['image'])?>" onerror="this.src='<?php echo url_for('../images/staff/profile.jpg') ?>'" style="border:1px solid #ddd;border-radius:2px; box-shadow: #4a5f63; height: 70px;width: 70px"></td>
<td><?php echo h($all_admins['first_name']) ?></td>
<td><?php echo h($all_admins['last_name']) ?></td>
<td><a class='btn btn-info' href="staff.php?source=show_staff&staff_id=<?php echo h($all_admins['id']) ?>"> <?php echo h($all_admins['email']) ?> </a></td>
<td>
<?php
$role = $all_admins['role'];
switch ($role){
case 'DE':
echo "Data Entry";
break;
case 'GU':
echo "General User";
break;
default:
echo "Administrator";
break;
}
?>
<span>
<select id="urole" name="role[]">
<option value="Admin" <?php echo ($role == 'Admin')?'selected':'' ?> >Admin</option>
<option value="DE" <?php echo ($role == 'DE')?'selected':'' ?> >Data Entry</option>
<option value="GU" <?php echo ($role == 'GU')?'selected':'' ?> >General User</option>
</select>
</span>
</td>
<td><a class='btn btn-info' href="staff.php?source=edit_staff&staff_id=<?php echo h($all_admins['id']) ?>">Edit</a></td>
<form method="post">
<input type="hidden" name="post_id" value="<?php //echo $post_id ?>">
<?php
echo '<td><input class="btn btn-danger" type="submit" name="delete" value="Delete"></td>';
?>
</form>
</tr>
$(document).ready(function ()
{
$("#urole").change(function (){
var val = $("#urole option:selected").val();
console.log(val);
// $("#urole").on('click', function(){
// v
// });
//displayData(val);
});
$("#urole").ready(function (){
var val = $("#urole option:selected").val();
console.log(val);
//displayData(val);
});
});
function displayData(query){
$.ajax({
url:"enrolled_learners/enrol_learner_provider.php",
method:"post",
data:{query:query},
success:function (data)
{
//console.log(data);
$('#q-provider').html(data);
}
});
}
</script>
Your issue is that you're using duplicate ids which is not valid. element ids must be unique. As such $("#urole") is internally designed to return only one element. Instead, you should use a common class on these elements and use $(".urole") to target all elements that have that class.
Change your form to
<select class="urole" name="role[]">
And your jQuery to:
$("#urole").change(function (){
var val = $(this).val();
console.log(val);
displayData(val);
});

jquery $.post fails to send data on second request

I have a bunch of records from a database that I am displaying on a page. Each record has their own form with an update and delete button. I'm using JQuery ajax to send the data to a PHP page to process the form.
The script works fine the first time I push any one of the buttons on any of the forms, but when I push another button on any of the forms (or even the same button on the same form) the ajax request doesn't send any of the data to the PHP page.
Code I'm using to output data on page:
<?php
foreach($records as $data) {
?>
<form>
<input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" />
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
</form>
<?php
}
Javascript:
$(document).ready(function() {
var buttonName;
$('input[type=submit]').click('click', function() {
buttonName = $(this).attr('name');
});
$('form').on('submit', function(e) {
e.preventDefault();
var values = $(this).serializeArray();
console.log(values);
if(buttonName == 'delete') {
var message = confirm('Are you sure you want to delete this record?\n\n You can\'t get it back once you do.');
} else {
message = true;
}
if(message) {
$.post('submit/raw_et.php', {et: values[0].value, token: values[1].value, id: values[2].value, button: buttonName}, function(r) {
console.log(r);
});
}
});
});
PHP Snippet:
echo $_POST['button'];
echo $_POST['et'];
echo $_POST['id'];
The "values" variable in the javascript always has the correct data, but the ajax fails to send any data after the first time a button is pushed and the results return blank.
I don't understand why it won't send the data. Am I missing something really easy, or is it something more complicated?
Edit:
I've taken out the tables in the html, but still get the same results.
you are developing in a completely wrong pattern, instead of defining form inside tr, use record id and register event for clicking buttons:
<?php
foreach($records as $data) {
?>
<tr>
<td><input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" /></td>
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<td><a class='edit' meta-id="<?php echo $record; ?>">edit</a></td>
<td><a class='delete' meta-id="<?php echo $record; ?>">delete</a></td>
</tr>
<?php
}
?>
And now, try to register all buttons onclick for delete and edit.
$(".edit").click(function() {
var record = $(this).attr("meta-id");
$.post("edit uri" , {record : record , otherparam: valueofit} , function(result) {
alert(result);
});
});
$(".delete").click(function() {
var record = $(this).attr("meta-id");
$.post("delte uri" , {record : record} , function(result) {
alert(result);
});
});
You can expand the concept as you want, for less adding class to buttons or so on.

Passing a value through Button to Php function

I am beginner in php and I am currently working on admin panel (you can see my admin panel page). The thing is that I want to pass serial number through these two buttons to perform further. But I can't find how to send $value to edit and delete a particular line.
<div id="headin2"><strong> <h3>Admin page </h3></strong></div>
<?php
echo "<table width=\"100%\" border=\"0\" id=\"tab\">";
echo "<tr>";
echo "<th id=\"td1\">Serial No</th><th id=\"td2\">Account Title</th>
<th id=\"td3\">Email</th><th id=\"td4\">Gender</th><th id=\"td5\">city</th>
<th id=\"td6\">Course</th><th id=\"td7\">status</th><th id=\"td8\" colspan=\"3\">Action</th>";
echo "</tr>";
while ( $row = mysql_fetch_array($query))
{
$SN = $row['SN'];
$actitle = $row['ac_title'];
$email = $row['email'];
$gender = $row['sex'];
$cite = $row['city'];
$course = $row['CRS'];
$status = $row['status'];
echo "<tr>";
echo "<td>".$SN."</td><td>".$actitle."</td><td>".$email."</td>
<td>".$gender."</td><td>".$cite."</td><td>".$course."</td><td>".$status."</td>
<td>"."<input type=\"button\" name=\"edit\" value=\"Edit\"/>
<input type=\"button\" value=\"Delete\" name=\"delete\" >"."</td>";
echo "</tr>";
}
?>
</table>
You need both the action (edit/delete) and the row id. Unfortunately, without some JS the button will only post one value.
You can create a new form for each row, add in a hidden element. For example:
<?php while ($row = mysql_fetch_array($query)) : ?>
<tr>
<!-- other cells -->
<td>
<form method="post" action="">
<input type="submit" name="action" value="Edit"/>
<input type="submit" name="action" value="Update"/>
<input type="hidden" name="id" value="<?php echo $row['id']; ?>"/>
</form>
</td>
</tr>
<?php endwhile; ?>
Then after posting it you can just check for the action and id
if ($_POST['action'] && $_POST['id']) {
if ($_POST['action'] == 'Edit') {
// edit the post with $_POST['id']
}
}
You can do it one of two ways.
jQuery and AJAX
For each <tr>, everywhere there is a delete button,
Delete
Script at the bottom:
//Include jQuery here
<script language="javascript">
$('.delete-row').click(function (event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax({
url: "url/to/delete",
method: "POST",
cache: false,
data: { id: id },
success: function (html) {
$(this).parent().parent().remove();
});
});
});
</script>
This puts the ID of the row into the <a href> itself using data and uses jQuery to send out an AJAX call to delete the record. If the delete is successful, it removes the row from the table.
Old-School Button
For each <tr>, everywhere there is a Delete button,
<form method="POST" action="url/to/delete">
<input type="hidden" name="id" value="<?php echo $value; ?>" />
<input type="submit" value="Delete" />
</form>
This is the old-school way to do it, where the hidden field is how the backend knows which row to delete.
On the backend, you still use $_POST['id']; to get the ID of the record to remove. In the above examples, $value is the ID for each row, and is most likely something like $row['id'] when it is coming from a foreach().
Use a hidden input (e.g.<input type="hidden" value="your_value_here">)
when you click Edit it open a page with corresponding record. You can do it by a Edit link or a image or a button.
<?php echo "<a href='".BASE_URL."admin/edit.php?id=$id' target='_blank'> <img src=".BASE_URL."/images/edit.png width=16 height=16 alt=Edit /> </a>";?>
for delete you can use jquery. here is a example
echo "<a href='#' onclick='deletePrescription($id)' ><img src=images/document_delete.png width=16 height=16 title='Delete Prescription' alt=Delete /> </a>";
<script type="text/javascript">
function deletePrescription(checkup_id) {
//alert(checkup_id);
var agree=confirm("Do you really want to delete the prescription?");
if (agree)
{
$.ajax
({
type: "POST",
url: "delete_prescription_admin.php",
data: "checkup_id="+checkup_id,
success: function(msg)
{
//
//alert( "array Updated: " + msg );
location.reload(true);
}
});
}
else
{
return false ;
}
}
</script>
PHP is on the server side, so you need to send parameters, parse it and have your php act.
i.e.
The edit button will make POST or GET request with parameter: id=123&action=edit
and your PHP will parse the Query String:
$strID = $_GET['id'];
$strAction = $_GET['action'];
then act on it..
if ($strAction=='edit'){
// do something...
}
Your buttons should be wrappen in a form like:
<form action="yourFile.php?id=<?=$SN ?>&action=edit" method="GET" id="formEdit<?=$SN ?>">
<button type="submit" value="Edit">
</form>
<a href=register_course.php?id=$roll&code=".$row['course_code']."&name=".$row['course_name']."><input type=submit value=Register>
*here register_course.php is the file where you are sending some variable having some data it will be delivered when button is clicked whose value is register //course code is the variable you want to send ... im assigning its value as $ code... and assigning id $roll as id and assigning course_name as $name....
the other file will get the variables having some data

How can I capture a variable inside a while loop, with ajax?

I have a loop to answer questions that looks something like this:
<?php
while ($u=mysql_fetch_array($result)){
?>
<table>
<tr>
<td>Question_ID</td>
<td>Question</td>
<td>Answer</td>
</tr>
<tr>
<td><? echo $u['question_id'];?></td>
<td><? echo $u['question'];?></td>
<td>
<form>
<input type="hidden" value="echo $u['question_id'];?>" />
<input type="text"/>
Send Answer
</form>
</td>
</tr>
</table>
<?php
}
?>
If the user answers for example the third question that appears on the page, my question is how do I capture the text written and the question_id so I can send those variables to a php page?
<script>
function ajax_answer(){
$.ajax({
question_id = ??? //how do I capture this variable?
answer = ??? //how do I capture this variable?
url:'answers.php',
type:'POST',
dataType:'text/html',
data:'question_id='+question_id + '&answer='+answer,
success: function(){
};
});
};
</script>
Thanks!
You're not giving them an id. I would give the a tag an id with a prefix so that you can use the same id to get your related input value:
<a href="#" id="q<php echo $u['question_id'];?>" // note that I added a "q" prefix
Then you should be able to get that via jQuery like this:
var theid = $(this).attr('id'); // this being the a tag that was clicked
// then just strip off the leading "q" and you have your id.
var thehiddenid = theid.replace('q', '');
If you want to do it in pure javascript,
then pass this to your ajax_answer function from onclick event like below
<?php
while( $u = mysql_fetch_array( $result ) ) {
?>
<tr>
<td><?php echo $u['question_id'];?></td>
<td><?php echo $u['question'];?></td>
<td>
<input type="hidden" value="<?php echo $u['question_id'];?>" />
<input type="text" />
Send Answer
</td>
</tr>
<?php
}
?>
and your javascript will be...
<script type="text/javascript">
function ajax_answer( elem ) {
var question_id = elem.parentElement.children[0].value;
var answer = elem.parentElement.children[1].value;
/// do your request here
return false;
}
</script>
And the same with jQuery.
Add name attribute to those input elements, and add a classname to anchor element
<?php
while( $u = mysql_fetch_array( $result ) ) {
?>
<tr>
<td><?php echo $u['question_id'];?></td>
<td><?php echo $u['question'];?></td>
<td>
<input type="hidden" name="question_id" value="<?php echo $u['question_id'];?>" />
<input type="text" name="answer" />
Send Answer
</td>
</tr>
<?php
}
?>
Javascript
add the onclick event handler dynamically. Now your function ajax_answer accepts two parameters question_id and answer, we will pass those two parameters through the click event handler
<script type="text/javascript">
$(function() {
$("a.send_answer").on("click", function( event ) {
event.preventDefault();
var td = $(this).parents("td:first");
var qid = $("input[name=question_id]", td).val();
var ans = $("input[name=answer]", td).val();
ajax_answer( qid, ans );
});
});
function ajax_answer( question_id, answer ) {
/// do your request here
}
</script>
You change your form and add id for easier selection:
<form>
<input type="hidden" value="<?php echo $u['question_id'];?>" id="question_id" />
<input type="text"/>
Send Answer
</form>
Then get the values like this:
question_id = $("#question_id").val();
Or if your form has only one hidden field for question_id:
question_id = $("input[type=hidden]").val();
Note: please consider to use <?php tags not short tags <?

form doesn't get submitted on an auto refreshed page

I have web application in PHP and i need some variables in this page to get refreshed automatically. Therefore i have put that processing in another page - "test.php" - which gets loaded into this div every 10 seconds.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval( function ()
{
$('#refresh').load('test.php').fadeIn("slow");
}, 10000);
</script>
</head>
<body>
<div id="refresh">
</div>
</body></html>
The problem is that this page has a form which on clicking, doesn't not submit the values and do the processing as it is supposed to do. Without the auto refresh code, it works fine. How do i overcome this problem?
the test.php contains this form:
<form action="count.php" method="post">
<?php
$votes = getVoteCount($popular[$i][1]);
$voted=checkVoted($screenName,$id);?>
<td><img src="<?php echo $popular[$i][4]; ?>" width=60></td>
<td align="center"><CITE><?php echo "#".$username; ?></CITE>
<?php echo "<br >".$text.
"<br >".$votes." votes |";?>
<?php
if($screenName!=$username && $voted==false){
?>
<input type="hidden" name="addID" value="<?php echo $id;?>">
<input type="hidden" name="username" value="<?php echo $screenName;?>">
<INPUT TYPE="image" src="images/vote.png" name='vote' ALT="Submit Form" onMouseOver="this.src='images/vote_link.png'"
onMouseOut="this.src='images/vote.png'" width="35" height="20" title="Click to Vote!"></form>
<?php }else if($voted){ ?>
<img src="images/voted.png" width="35" height="20" title="You have already voted">
<?php } else{
echo "<img src='images/authored.png' width='40' height='20'>";
}?>
Because you're reloading the page with ajax requests you no longer can use
$("submit-button").click()
or
$("submit-button").submit();
You will need to use either jquery's live, delegate, or on to do this. (Live is no longer a recommended way of doing this.
$("body").on("click", "submit-button", function()
{
//execute code here
});
or
$("body").on("submit", "submit-form", function()
{
//execute code here
});

Categories