Passing a value through Button to Php function - php

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

Related

how to check if a checkbox is checked when sending data via ajax to php

I have a foreach loop which creates tr's with inside a checkbox and some input fields.
Each row has a checkbox with the id as value.
Each row has also a hidden input field with the id as value.
I want to distinguish whether a request is send via the own delete button in each row, or via the checkbox what is checked for (these) rows. (when multiple checkboxes are checked, i can delete them all at once)
<tr>
<input type="hidden" name="file_id" value="<?php echo $file_id; ?>" /> <!-- file id which belongs to each row -->
<td><input type="checkbox" class="checkbox" value="<?php echo $file_id; ?>" /></td>
...
<button class="btn btn-sm btn-danger submit" type="submit" name="delete_file">Delete</button>
</tr>
i send the data via jquery ajax to the php file:
// checkboxes value
$(document).on('click' , '.submit' , function() {
var checkbox_value = [];
var file_id = $(this).closest("tr").find("input[name='file_id']").val();
$('.checkbox').each(function() {
if ($(this).is(":checked")) {
checkbox_value.push($(this).val());
}
});
checkbox_value = checkbox_value.toString();
$.ajax({
url: "admin.php",
method: "POST",
data: {
checkbox_value: checkbox_value,
file_id : file_id
},
success: function(data) {
$('.result').html(data);
}
});
});
The php:
if(isset($_POST["checkbox_value"])) {
$checkboxfiles[] = $_POST["checkbox_value"];
$category = $_POST["category"];
// checkbox loop
foreach ($checkboxfiles as $checkboxfile) {
foreach(explode(',', $checkboxfile) as $id) {
echo $id.'<br />';
echo 'delete via checkbox is choosen';
}
}
exit;
}
if(isset($_POST["file_id"])) {
...
echo 'delete via single row is choosen';
}
Problem:
When i choose to delete via single row (no checkbox is checked), it still sends the echo delete via checkbox is choosen
try this code
if (this.checked) {
checkbox_value.push($(this).val());
}

Dynamically load modal-dialog in one page

I have a table in one page where each row refer to a modal dialog with form...
It's all loaded from mysql db with php
For example
SELECT id, name FROM db
While fecth() .... {
<tr>
<td><button data-target="#modal_<?php echo $id; ?>">show first</button>
<div id="modal_<?php echo $id; ?>">
<form action ...>
<input type="text" value="<?php echo $name; ?>">
<input type="hidden" value"modal<?php echo $id; ?>">
<input type="submit" value="submit">
</form>
</div>
</td>
<td><?php echo $name; ?></td>
</tr>
}
There can be lot of row in a table and this weighs the page... The source was very long
How can I write one modal dialog and then load based on ID ?
The very simple and straight solution is;
If you are using jQuery UI Dialog
For Reference, the page name index.php and displaying fetched data from database (as stated in question)
Replace data-target="#modal_<?php echo $id;?>" with class="open" id="<?php echo $id; ?>"
bind open selector with jQuery click function
$(".openmodal").click(function();
create variable id and fetch id="<?php echo $id; ?>" from button attribute.
var id = $(this).attr("id");
Use Ajax Method to fetch data against the id and show in modal
Modal open button will be
<tr>
<td><button class="open" id="<?php echo $id; ?>">show first</button></td>
<td><?php echo $name; ?></td>
</tr>
And Modal HTML will be
<div id="dialog" style="display:none;">
<div id="Schedule"></div> //Here we show the content in Modal
</div>
and Ajax Method will be
$(document).ready(function(){
$(".openmodal").click(function() {
var id = $(this).attr("id");
alert(id);
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
$("#dialog").dialog();
$("#Schedule").html(data);
}
});
});
});
Now create ajax.php to use in Ajax method;
<?php
//connection to the database
if($_POST['id']) {
$id = $_POST['id'];
//Run Query to fetch the data against `$id`
?>
//This form with fetched detail from database will show in Modal
<form action="" name="" class="" id="">
<input type="text" value="<?php echo $variable; ?>">
<input type="submit" value="submit">
</form>
<?php } ?>
And if you are using bootstrap modal you can check this answer.

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.

Display records on load page using jquery ajax in php

I want to load data when page is loaded but if i try doing that then delete function doesn't work and whenever I insert the effect should be seen in table without refreshing page Please check my code what changes to be done in this
index.php
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#Submit").click(function(e) {
var name = $('#name').val();
var message=$('#message').val();
if($(":text").val().length==0)
{
$(":text").after('<span class="error">Field cannot be empty</span>');
$('#name').addClass('error');
$('#message').addClass('error');
return;
}
else{
$('#name').removeClass('error');
$('#message').removeClass('error');
//$('#propspectDiv').removeClass('error');
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');
$.ajax({
url : 'data.php',
data:{
"name" : name,
"message" : message
},
success : function(data){
window.setTimeout(function(){
$('#propspectDiv').html('Your Name is added to our records');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
},
complete:function(){
$('#myform').each(function(){
this.reset();
});
}
});
}
});
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
});
</script>
</head>
<body>
<form id="myform">
<div id="wrapper">
Name : <input type="text" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
<input type="button" value="Submit" id="Submit" />
<div id="propspectDiv"></div>
<table id="data" border="1" style="display:none;"></table>
</div>
</form>
</body>
data.php
<?php
$name = $_REQUEST['name'];
$message = $_REQUEST['message'];
include('connection.php');
$sql = "INSERT INTO login (username,message) VALUES ('$name','$message')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
echo'<tr>';
echo'<td>SrNo.</td>';
echo '<td>Name:</td>';
echo '<td>Message:</td>';
echo '<td>Delete</td>';
echo'</tr>';
$i=1;
while($row = mysql_fetch_array($res))
{
echo '<tr>';
echo'<td>'.$i.'</td>';
echo'<td>'.$row['username'].'</td>';
echo '<td>'.$row['message'].'</td>';
echo"<td id=td1>
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
echo '</tr>';
$i++;
}
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: index.php");
}
?>
Looks like your grabbing the ID attribute of the link, but not setting it...
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
There is no ID attribute on your existing delete link:
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
Also - you probably don't need to have the link href pointing to delete.php as its irrelevant when the jquery click event does all the work.
Also, because you are inserting the html (including the delete method) via jquery you may need to use the "on" event
I'm doing this off the cuff so the code may have some minor bugs but I believe this is the path you want to take...
Revised it might look like this:
JQUERY
$("a").on("click", function(e) {
e.preventDefault();
$.post('delete.php',{ id: $(this).attr("id")});
return false;
});
LINK
echo"<td id=td1>
<a id='".$row['id']."' href='#'>Delete</a>";
echo '</tr>';
couple things to note...
1 - above i'm not actually VERIFYING the record was deleted before I remove the appropriate table row - you may want to implement something to check this
2 - an alternative to removing the table row would be to just update the table in general by repulling the data and outputting it - if you know what i mean

Making table cells clickable

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>.

Categories