This is a tough one to explain...
I'm developing a restaurant system where the user add the dishes available to sell, but the user has to have an option to edit/delete AFTER the dish was registered.
So what i thought was: k, gonna make a table fetching the data from the DB and in the last column put some options like edit/delete... Here is the code for better understanding:
foreach ($result as $row){
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.'<img src="img/icons/16/delete.png" alt="delete" height="16" width="16">'.'</td>';
echo '</tr>';
}
Like you've saw the delete option has already there (with no function/action yet) Here is the thing... I could put a link to a file in href="delete.php? but when a user clicks on this link will lead them to the delete.php page, leaving the administration page... I would like that when the user clicks the delete img, worked as/similar AJAX. I don't want the user exit the page....
Sorry for bad english (not my mothertongue), if you guys want more details just ask.
Ps: New PHP Programmer
Thanks in advance.
use javascript or jQuery to do an ajax request to delete.php with the id of the row you want to delete. I often put the id in the <tr> like echo "<tr data-id='{$row['id']}'>" and my jQuery would look something like this
$(".delete").on('click', function() {
var id= $(this).parents('tr').data('id');
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success:function(data, textStatus, jqXHR) {
// do something with the data returned. I usually output "success" from my
// delete.php and then check for data.indexOf('success') != -1
$("tr[data-id="+id+"]").remove();
},
error:function(jqXHR, textStatus, errorThrown) {
alert("Error: "+jqXHR+" "+textStatus+" "+errorThrown);
}
});
});
on my delete.php page i check that $_POST['id'] is not empty before continuing. If you use $_REQUEST['id'] it will also work with a direct link to delete.php?id=999
You can call Delete.php using AJAX, so the request is executed without leaving the page.
The advantage of making an actual link to the delete page, is that it also works without Ajax/Javascript. So you can start by building a plain delete page, and add the Ajax later.
First, you should also print a record_id because just deleting based on the name is a very bad idea where encoding will hunt you down.
Having said that, here is what I would do using jQuery:
//PHP
foreach ($result as $row){
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.'<img class="delete-btn" src="img/icons/16/delete.png" alt="delete" height="16" width="16" data-order-id="$row['id']">'.'</td>';
echo '</tr>';
}
//JQUERY
$(document).ready(function(){
$(".delete-btn").click(function(){
$.post("/delete.php", {order_id: $(this).attr("data-order-id")}, function(){
$(this).closest("tr").remove();
});
});
});
Related
The code below is a php code where i have retrieved data from a database,the code is executing well .My main problem is,on click this link 'send offer' in the following reference link (send offer),i need to get only the id of the particular data without loading to another page and loop it with jquery.For instance on click the id='buyerRequest',i need to insert data of that user into the database without loading the page and in addtion to disable the other links.
The code below is a php code where i have retrieved data from a database,the code is executing well .My main problem is,on click this link 'send offer' in the following reference link (send offer),i need to get only the id of the particular data without loading to another page and loop it with jquery.For instance on click the id='buyerRequest',i need to insert data of that user into the database without loading the page and in addtion to disable the other links.
<?php
require'php/connection.php';
$user_name=getUserField('user_name');
$query="SELECT * FROM `place_order` where `buyer_name` != '$user_name' order by `order_id` DESC";
if($query_run=mysql_query($query)){
echo"<table id='table_request'>";
echo"<tr id='tr_request'>";
echo"<td>Date</td>";
echo"<td>Order Description</td>";
echo"<td>Bid</td>";
echo"<td>Order By</td>";
echo"<td>Send Offer</td>";
echo"<br></tr>";
while($fetch_num=mysql_fetch_array($query_run)){
echo"<tr id='fetch_request'>";
echo"<td>".$fetch_num['current_date'].'</td>';
echo"<td>". $fetch_num['desc_order'].'</td>';
echo"<td>". $fetch_num['order_id'].'</td>';
echo"<td>". $fetch_num['buyer_name']."</td>";
echo"<td id='td_request'><a id='buyerRequest' href='SendingOffer.php?id=".$fetch_num['order_id']." ' >send offer</a></td>";
echo"</tr>";
}
echo"</table>";
}
?>
**Jquery code**
$('#buyerRequest').click(function(){
$('#id').each(function()
{
var id=$(this).attr('id');
alert(id);
});
});
<a class='buyerRequest' data-id='".$fetch_num['order_id']."' href='SendingOffer.php?id=".$fetch_num['order_id']." ' >send offer</a>
Adding data attribute to element makes thing easier ( data-id )
$('.buyerRequest').click(function(){
var order_id = $(this).data('id');
alert("Order_id: " + order_id);
});
<a id='buyerRequest' data-id='".$fetch_num['order_id']."' href='SendingOffer.php?id=".$fetch_num['order_id']." ' >offer sent</a>
jQuery(document).ready(function(){
jQuery("#table_request tbody").on('click', '#buyerRequest', function(event) {
var id=jQuery(this).data("id");
alert(id);
});
});
Please Use tbody in your table.I think it will help you.
Try This,
<a id='id_".$fetch_num['order_id']."' class="buyerRequest" href='#'>send offer</a>
$('.buyerRequest').click(function(){
var id=$(this).attr('id').replace('id_','');
alert(id);
var data1 = {id: id};
jQuery.ajax({
data:data1,
type:'POST',
url: 'SendingOffer.php',//set full url
success:function(strHTML)
{
$(this).attr('disabled','disabled');//this is disable a link you want to clicked
}
});
});
I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.
I am developing a plugin for WordPress system for some custom media review purpose. I have setup most of the things but few more.
Currently I stuck on the part to update database on click ( onlink ) to update table value using AJAX. Refer below code. It has while loop and I want to use AJAX within the loop to update media status. I am not sure is this the right way or there is another simple way to make it happen. Any suggestion would be appreciated.
Code:
<?php
$media_item = mysql_query($media_sql);
if ($media_item) {
echo '<ul class="rm-media-list">';
while ($media = mysql_fetch_array($media_item)) {
$m_uid = $media['user_id'];
$m_uname = $media['user_login'];
$media_class = new q2a_review_media;
$thumb_path = $media_class->rm_thumbnail_url($pid,$m_uid);
$media_url = $media_class->rm_media_url($pid,$m_uid);
$mediaid = $media['id'];
$image_name = $media['image_name'];
echo '<li>';
echo '<span class="rm-media-user">',$m_uname,'</span>';
echo '<a href="'.$media_url.$image_name.'" rel="lightbox['.$pid.']" title="Post: '.$pid.' | '.$ptitle.' | Image: '.$image_name.' | by: '.$m_uname.' " ><img src="'.$thumb_path.$image_name.'" alt="'.$media['image_name'].'" width="56" class="rm-thumbs-list" /></a>';
echo '<span class="rm-action-links"><a href="#" id="approve-'.$mediaid.'" >Approve</a> | <a href="#" id="delete-'.$mediaid.'" >Delete</a></span>';
echo '</li>';
}
} else {
echo 'No media found';
}
echo '</ul>';
?>
Database Table:
My Plugin Page Output
In above image you can see link called Approve | Delete Here I want to make interaction with database using ajax. When admin click on Approve it will update value from 0 to 1 in status column and when Delete than it will delete the row and images from the directory. Hope I posted enough data to understand. If not please let me know I will try to add some more information.
Million thanks.... :)
Firstly, your statement echo '</ul>'; needs to be in the if part of the loop.
Your AJAX code doesn't have to be inside the while loop. Here is how you can manipulate your code to make an AJAX request.
Let's first modify your <a> tag slightly:
Approve
This change allows you to have a group of buttons with class="approve-button" and id="the id of the item you want to approve"
Now, we can use some JavaScript to make an AJAX request. For convenience, I will use jQuery to make this request:
<script type="text/javascript">
//Attach an onclick handler to each of your buttons that are meant to "approve"
$('.approve-button').click(function(){
//Get the ID of the button that was clicked on
var id_of_item_to_approve = $(this).attr("id");
Make an AJAX request
$.ajax({
url: "some-page.php", //This is the page where you will handle your SQL insert
type: "post",
data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
success: function(){
console.log("AJAX request was successfull");
},
error:function(){
console.log("AJAX request was a failure");
}
});
});
</script>
As far as some-page.php goes, this is what you need to do:
Have your SQL statements that will make the changes to he database
To access the ID attached to the approve button that was clicked, you can use the $_POST array since the AJAX request was of type "post". Specifically, this is where your ID is stored: $_POST['id']
FYI: To import jQuery on your page, you can use:
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>
I am fetching a problem though I know it's not a big issue, but something is different to me as I new. I have a page which has a list of records, fetching from a database. Now one button is there , after clicking the records, one pop up will be opened up along with some data. Inside that pop up one another link is there called "restore", whenever , that linked will be clicked out the database has been updated. Now up to this its okay for me. But whenever, I close the pop up, my list of records should automatically changed as some records have been restored. But I am not getting the result until and unless I do not refresh the page. so how can I do this, please help me ....
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "restore-request-process.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
//return false;
});
});
in the restore-request-process.php page I just update the database and echo the id.
After the database update, call a function to update the front end or simply reload page using location.reload()
you need to have declared global function in parent window
function Update(){
//global function in parent, update div
}
on popup window call function
window.opener.Update();
that will automatic reload your div, and not all page, If it's not necessary
Suppose this is your listing format
<table>
<?php
foreach($results as $result) { ?>
<tr id="my_div">
<td><?php echo $result->name?></td>
<td class="delete" id="<?php echo $result->id?>"><img src="delete.png"/></td>
</tr>
<?php } ?>
</table>
In restore-request-process.php write a query which fetch all the result from database and just echo the result like this
$result = mysql_query("SELECT * FROM my_table");
while($row = mysql_fetch_array($result))
{
echo '<td>'. echo $row["name"].'</td>
<td class="delete" id="'. echo $row["id"].'"><img src="delete.png"/></td>' ;
}
and onsuccess replaced all the content inside the my_div with response text
CODE IS NOT TESTED
for more references you can go through this link
I am really stuck and was wondering if someone could lend a hand please,
i know how to get a query string, thats not a problem,
however,
I have links that use jquery to fade out the content and load the new content via links,
usage example below - class="link2" is a reference for the jquery to do what it does lol
click here
in the href i have to have the # first to stop the page from loading if you get what i mean,
now when i try and get the query string id=2 it says none as there is a # first, there is probably a simple fix for this but i must just be missing it,
i have searched and searched but still cant find the answer
----------------------edit------------------------------
this is what i am trying to do,
enter page,
sql query runs to display all the reports
click a report and the jquery hides "contmain" and shows "contreports" now a new sql query runs to display the report based on the "id"
now usually i can just get this information from the url and clean it up, hovever as i have jquery running i need to have the "#" for the href so the page does not reload and the jquery can run, but now this is stopping me from being able to retrieve the url query,
Interstellar_Coder
he seems to have the right idea, passing it in the background
Although i don't fully understand what you're doing, i'm guessing it would be better to store your querystring as a data attribute.
click here
Then in your jQuery function.
$('.link2').click(function(e){
var queryString = $(this).data('id');
e.preventDefault(); // prevent the default action
});
because of the code i thought it best to post here
i think i am getting close,
#Interstellar_Coder - this is what i have so far but it only ever retrieves the first id,
$query1 = mysql_query("SELECT * FROM `".TBL_CATCH_REPORTS."` order by id DESC");
$query2 = mysql_num_rows($query1);
if(mysql_num_rows($query1) != 0) {?>
<table width="880" style="margin:0 auto">
<?PHP while ($output = mysql_fetch_assoc($query1)) { ?>
<tr class="row">
<td width="190px"><input type="button" class="c_report"value="<?PHP echo $output['id']; ?>" />
View Report <img src="images/icons/arrow_right.png" width="16" height="16" /></a></td>
<td width="210px">Submited by <?PHP echo $output['submitby']; ?></td>
<td width="160px"><?PHP echo $output['date']; ?></td>
<td><?PHP echo $output['title']; ?></td>
</tr>
<?PHP } ?>
</table>
<?PHP }else{ echo '.Sorry there are no catch reports yet'; }?>
<div id="contreport"> content here </div>
<script type="text/javascript">
$(document).ready(function(){
$(".c_report").click(function () {
$("#contreport").html('Getting Catch Report......');
$.ajax({
type: "POST",
data: "data=" + $(".c_report").val(),
url: "reportdata.php",
success: function(msg){
$("#contreport").html(msg)
}
});
});
});
</script>
my other page "reportdata.php just gets the value and is then used in a sql statement
$getreport = '';
if (isset($_POST['data']) and trim($_POST['data']) != '' ) {
$getreport = trim($_POST['data']);
}
i am assuming i need some kind of loop going on in the jquery but i am just lost, been stuck on this all day today again lol
this is all i need
id 1 - link
id 2 - link
id 3 - link
id 4 - link
id 5 - link
click on any and the id will be sent to reportdata.php where the id will be used in a sql statement, then the data returned and displayed,
its truly sending me mad lol