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.
Related
I have a form in PHP & MySQL and I want to submit it with AJAX.
I Have similar data so I have put these data in a foreach loop.
The problem is that when I try to submit the first row data it all goes well but it changes the data in all rows. and when I try to submit other data except the first row it doesn't submit at all.
I think the problem is because the submit button always gets the same id and therefore goes to the first row always.
I don't know how to get the value in Ajax.
Here goes the code:
//php form
<?php
$pid = $_GET['pid'];
include('config.php');
$timeline_query="SELECT * FROM timeline_table WHERE pid=$pid";
$result_timeline=mysqli_query($conn,$timeline_query);
if(!$result_timeline){
echo "Error: " . $conn->error;
}
$timelines=array();
while($row_timeline=mysqli_fetch_assoc($result_timeline)){
$timelines[]=$row_timeline;
}
?>
<?php
$x = 0;
foreach ($timelines as $timeline):?>
<div class="card">
<div class="card-header" id="heading<?php echo $x; ?>">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapse<?php echo $x; ?>" aria-expanded="true" aria-controls="collapse<?php echo $x; ?>">
<?php echo $timeline['timeline_title'];?>
</button>
</h5>
</div>
<div id="collapse<?php echo $x; ?>" class="collapse" aria-labelledby="heading<?php echo $x; ?>" data-parent="#accordion">
<div class="card-body">
<form id="register_form">
<input type="text" id="tid" name="tid" value="<?php echo $timeline['tid']; ?>"/>
<textarea class="form-control" rows="4" id="timeline_description" name="timeline_description"><?php echo $timeline['timeline_description'];?></textarea>
<input id="submit" type="submit" name="submit" value="Submit" />
</form>
</div>
</div>
</div>
<?php $x++; endforeach;
// ajax function
$(document).ready(function(){
$("#submit").click(function(){
var timeline_description = $("#timeline_description").val();
var tid = $("#tid").val();
alert(timeline_description);
alert(tid);
// Returns successful data submission message when the entered information is stored in database.
// var dataString = 'timeline_description='+timeline_description+'&pid='+ pid + '&tid='+ tid +;
var dataString = 'timeline_description='+timeline_description;
alert(dataString);
if(timeline_description=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "process.php?tid"=+tid,
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
//process.php
<?php
include('config.php');
$tid=$_GET['tid'];
if( $_POST['timeline_description']==NULL ){ $timeline_description=''; }
else { $timeline_description=$_POST['timeline_description']; }
$query_timeline = "UPDATE timeline_table SET
timeline_description='$timeline_description' WHERE tid=$tid ";
$result=mysqli_query($conn,$query_timeline);
if(!$result){
echo "Error: " . $conn->error;
}
?>
Any idea?
Id of elements must be unique. The abnormal behaviour of your code is due to non-unique ids of your input elements.
In the case, If you cannot assign unique ids to elements you can achieve desired output by using this keyword and siblings() method in jquery.
Instead of
var timeline_description = $("#timeline_description").val();
var pid = $("#pid").val();
var tid = $("#tid").val();
try to get values in this way.
var timeline_description = $(this).siblings('#timeline_description').val();
var pid = $(this).siblings('#pid').val();
var tid = $(this).siblings('#tid').val();
I see there a problem with Yours inputs id - <input type="text" id="pid" - this is in foreach, so You have multiple elements with same id. So var pid = $("#pid").val(); will return You always a value of first found element. Try to use arrays:
<input type="text" id="pid[$pid]" name="pid[$pid]" value="<?php echo $pid ?>"/>
<input type="text" id="tid[$pid]" name="tid[$pid]" value="<?php echo $timeline['tid']; ?>"/>
Please remember one thing: id of any element in html PAGE (whole document) must be unique.
I'm using the code below to loop through my database rows and display the info. Each form has a delete button that should delete that row from the database :
function show_scheduled_tweets () {
global $wpdb;
$query = "SELECT * FROM wp_tweettweet";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$tweet2 = $result[text];
$recycleOption = $result[recycle];
$id = $result[id];
?>
<form id="tweet-<?php echo $id; ?>" class="tweetclass form-inline" action="" method="post">
<div class="checkbox">
<label>
<input type="checkbox" name="recycle" <?php if($recycleOption == 1){ echo "checked";} ?>>Recycle Tweet?
</label>
</div>
<div class="form-group"><input class="form-control" type="text" name="tweet" value="<?php echo $tweet2; ?>"></div>
<div class="form-group"><input class="form-control" type="text" name="tweetdate"></div>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="form-group"><input class="form-control" type="text" name="timepicker" class="timepicker"/></div>
<input class="tweetsubmit" type="submit" value="Save">
<input class="tweetdelete" type="submit" value="delete">
</form>
<?php
}
}
show_scheduled_tweets();
Here is my Ajax :
jQuery('.tweetdelete').click(function(event) {
event.preventDefault();
var id = jQuery('input[name="id"]').val();
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: {
'action': 'db_tables_delete',
'id': id
},
beforeSend: function() {
alert('before')
},
success: function(){
alert('success')
},
error: function(){
alert('error')
},
});
});
Let's say I have five different rows of data showing. Now matter which delete button I click, the top row will always be deleted. In other words, if I click the delete button for row 3, the first row will be deleted.
As per your current code val() returns value of first element. Check the description from documentation :
Get the current value of the first element in the set of matched elements or set the value of every matched element.
You need to get the id value based on clicked element, use prevAll()
var id = jQuery(this).prevAll('input[name="id"]').val();
or siblings() method
var id = jQuery(this).siblings('input[name="id"]').val();
or with closest()(or parent()) and find()
var id = jQuery(this).closest('form').find('input[name="id"]').val();
Your selector for the US is not particular to the tweet in the firm. The event passed to the JS function will carry with it a target (which will be the button that was clicked), if you echo your $id into a data attribute of that button then the relevant id it will be accessible within the target:
<input data-id="<?php echo $id;?>" class="tweetdelete" type="submit" value="delete">
and in your JS:
var id = jQuery(event.target).attr('data-id');
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.
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
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>.