Solved

Getting the value of a clicked button from a list of submit buttons

Posted on 2014-04-24
17
243 Views
Last Modified: 2014-04-25
I display rows of mySQL records with two buttons - Edit and Delete, at the end of each  row.  A user is supposed to click either edit or delete of a chosen row and be presented with the contents of the chosen record on a form. She/he can then edit the contents of the form and submit or delete as the case may be.

I use ajax/jquery to retrieve the value of the clicked button and php to process the input. I am having hard time displaying the records appropriately and retrieving the value of the selected button using ajax/jquery. Once retrieved I would use php to process it and display a confirmation message in a div.

1. Is it better to have a separate form for each pair of edit/delete buttons? Would that mean a unique id for every form to distinguish it from the rest? That is, if on form submit is to be used in ajax/jquery. OR
2. Use the same form for all the buttons and get the value of the clicked button (either edit or delete) and the record id associated with it?
3. How would the html/php code to list the mySQL records and the ajax/jquery code retrieve the values look like?

Your quick help is deeply appreciated.
0
Comment
Question by:davidgm
  • 10
  • 7
17 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 40022046
I would use the data attribute

So
<input type="button" value="Edit" class="action edit" data-id="1" />
<input type="button" value="Delete" class="action delete" data-id="1" />

...
<script type="text/javascript">
var url = 'ajax_script.php';
$(function() {
  $('.action').click(function(e) {
     e.preventDefault();
     var id = $(this).data('id');
     var action = $(this).hasClass('edit') ? 'edit' : 'delete';
     $.ajax(
         url: url,
         data: {id: id, action: action},
         type: 'POST',
         success: function(result) {
           // process return here. This could be to display a popup window
           // with either a confirm for delete or a form for edit
         }
       );
  });
});
</script>

Open in new window

In the above code we give our edit and delete buttons (which can be buttons or <a> or anything) a class of action to identify them as buttons we want to catch the click event for.
We then give the edit buttons an edit class and the delete buttons a delete class. We do  this because we are going to trap the event based on the .action class.

In the event handler we pull the id by accessing the data-id attribute using the JQuery .data method. You would use the corresponding record id for each pair of edit / delete buttons.

The action is set by checking for the edit class - if it exists then action is edit otherwise it is delete.

That's pretty much it - you have all the info you need to call your ajax function (bar any other data you are passing back as part of the edit)
0
 

Author Comment

by:davidgm
ID: 40022495
Thanks for your reply julianH.

I am implementing your solution. I am assuming in - data-id="1", the 1 would be replaced by the record number as pulled from the database? That is <?php echo $row["recordid"]; ?>. Is my assumption correct?
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 40022533
Yes that is correct. Each button pair would have the id of the record it correpsonds to.
0
 

Author Comment

by:davidgm
ID: 40022571
Thanks, working on it...
0
 

Author Comment

by:davidgm
ID: 40022681
It looks like I have put everything in place but clicking the buttons is not giving any response... like $('.action').click not being triggered....

I have put the ajax code in an include file as - EditDelete.js and called it as

<script type="text/javascript" src="EditDelete.js"></script>

and this is the code below (added an alert on data and then tried to display the result in a div called editRecord):

var url = 'editDelete.php';
$(function() {
  $('.action').click(function(e) {
     e.preventDefault();
     var id = $(this).data('id');
     var action = $(this).hasClass('edit') ? 'edit' : 'delete';
     $.ajax(
         url: url,
         data: {id: id, action: action},
         type: 'POST',
         success: function(result) {
			// process return here. This could be to display a popup window
           // with either a confirm for delete or a form for edit

		alert (data);

		$("#editRecord").html(result);



}
       );
  });
});

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 40022730
Added code tags to your post.

The problem is you are missing {} around your ajax parameters - should be

$(function() {
  $('.action').click(function(e) {
     e.preventDefault();
     var id = $(this).data('id');
     var action = $(this).hasClass('edit') ? 'edit' : 'delete';
     $.ajax({ // ADD { HERE
         url: url,
         data: {id: id, action: action},
         type: 'POST',
         success: function(result) {
            // process return here. This could be to display a popup window
            // with either a confirm for delete or a form for edit
            alert (data);
            $("#editRecord").html(result);
         }
     }); // AND HERE
  });
}); 

Open in new window

0
 

Author Comment

by:davidgm
ID: 40022735
Tried Firebug which indicated an error with $.ajax( ... ); and I added curly brackets $.ajax ({...}); but nothing changed. Click is not triggering anything.
0
 

Author Comment

by:davidgm
ID: 40022755
Just did that and tested... no change.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:davidgm
ID: 40022783
Code of a button with ids 29 and 30 for example looks like:

<input type="button" value="Edit" class="action edit" data-id="29" />
<input type="button" value="Delete" class="action delete" data-id="29" />

<input type="button" value="Edit" class="action edit" data-id="30" />
<input type="button" value="Delete" class="action delete" data-id="30" />
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 40022792
This works for me
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
var url = 'editDelete.php';
$(function() {
  $('.action').click(function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    var action = $(this).hasClass('edit') ? 'edit' : 'delete';
    $.ajax({
      url: url,
      data: {id: id, action: action},
      type: 'POST',
      success: function(result) {
        // process return here. This could be to display a popup window
        // with either a confirm for delete or a form for edit
        $("#editRecord").html(result);
      }
    });
  });
}); 
</script>
<style type="text/css">
</style>
</head>
<body>
<table>
  <tr>
    <td>Row1</td>
    <td>
      <input type="button" value="Edit" class="action edit" data-id="1" />
      <input type="button" value="Delete" class="action delete" data-id="1" />
    </td>
  </tr>
  <tr>
    <td>Row2</td>
    <td>
      <input type="button" value="Edit" class="action edit" data-id="2" />
      <input type="button" value="Delete" class="action delete" data-id="2" />
    </td>
  </tr>
  <tr>
    <td>Row3</td>
    <td>
      <input type="button" value="Edit" class="action edit" data-id="3" />
      <input type="button" value="Delete" class="action delete" data-id="3" />
    </td>
  </tr>
  <tr>
    <td>Row4</td>
    <td>
      <input type="button" value="Edit" class="action edit" data-id="4" />
      <input type="button" value="Delete" class="action delete" data-id="4" />
    </td>
  </tr>
</table>
<div id="editRecord"></div>
</body>
</html>

Open in new window

editDelete.php
<?php
$id = $_POST['id'];
$action = $_POST['action'];
?>
Action: <?php echo $action;?><br/>
This is the data for record <?php echo $id;?>

Open in new window

Working sample here http://www.marcorpsa.com/ee/t652.html
0
 

Author Comment

by:davidgm
ID: 40022838
Working on it...
0
 

Author Comment

by:davidgm
ID: 40022951
Tested it with IE, Firefox and Chrome. It worked! Do you recommend another function for the update and deletion? Will award you the full points...
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 40022980
Do you recommend another function for the update and deletion?
Not sure what the question is - can you elaborate?
0
 

Author Comment

by:davidgm
ID: 40023027
I guess that would be another question.... I was thinking about how to do the "delete" or "update" after the record has been identified and displayed. Whether it is better to modify and use the same ajax and php code or to use a fresh one.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 40023056
There are many ways to skin a cat - which way is best depends on the specifics of your implementation.

Here are some of the challenges you will face with doing this by AJAX.

1. You have to build and display the edit / delete form based on an AJAX return. Not too difficult you can just mark it up and display it in a popup - either your own or a JQueryUI dialog.
The dialog can either be sourced by AJAX or can be a template already in the page that is populated with data returned by the AJAX call. Each approach has its merits.

2. Validation will have to be built into the form - either as an included script in the returned form - or a script on the originating page. Either way you will need to look at dynamic binding - controls created on the page after load wont be bound to events unless you bind them with the .on() method.

3. The next step is submission - you will need to collect the data and submit it back for processing

4. You will need to refresh the screen with the updated information - either as a complete table redraw - or just the row affected. Again mertis / demerits with both.

One option is to implement the actual functionality for delete / edit inside an IFrame that goes back to a page on the server.

It is very difficult to recommend which way to go - it all depends on the framework you are using and how your code is strucutred and how comfortable you are with AJAX and the processing that goes with it.

There are a bunch of javascript frameworks out there that you could use - but you would need to take the time to learn how they work and many of them would require you design your application around them rather than just implementing for a particular instance.

One strategy is to build the Delete / Update cycle as separate pages - once that is working you can then Piggy Back the AJAX functionality on the back - either using an IFrame to those existing screens or retrieiving the HTML via AJAX and populating a popup.
0
 

Author Comment

by:davidgm
ID: 40023091
Excellent elaboration... very important what you have said regarding binding with .on() method.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 40023126
You are welcome - thanks for the points.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Introduction A frequently used term in Object-Oriented design is "SOLID" which is a mnemonic acronym that covers five principles of OO design.  These principles do not stand alone; there is interplay among them.  And they are not laws, merely princ…
A publishing tool, a Version Control System, or a Collaboration Platform! These can be some of the defining words for the two very famous web-hosting Git repositories: Bitbucket and Github. Git is widely used amongst the programmers and developers f…
The viewer will learn how to dynamically set the form action using jQuery.
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now