Passing one of the value to controller when clicking a button

Home / Uncategorized / Passing one of the value to controller when clicking a button

Question:
I have a table like this:

When I click the Delete! button, I want to pass the role ID to the controller.

After looking for a lot of cases in stackoverflow. I’ve just succeeded to retrieve the role ID using JS.

Code like this:$(".deleteButton").click(function() {
var $row = $(this).closest("tr");
var $text = $row.find("td:first-child").text();

// Let’s test it out
alert($text);
});

But the problem is, I don’t how to pass it back to the button, so then the button can pass it to the controller.

Is there any simple way to pass it to the controller? Maybe without retrieving the role ID first, and when click the button the value passed and the controller called at once?

This is my code:


ID Role Role Jumlah Member
id_role ?> role ?> jumlah ?>

Answer:
Do you have to use JavaScript? If not, this is a simple task for a form

foreach($result as $row) : ?>


id_role ?> role ?> jumlah ?>

Your controller would then receive either $_POST[‘edit’] or $_POST[‘delete’] with the role ID as the value.

If you’re interested in securing your form from possible cross-site-request-forgery attacks, CodeIgniter has a built-in solution.

Otherwise, I would just add the id_role property to the button, eg

and in your JS
$(‘.deleteButton’).on(‘click’, function(e) {
var roleId = this.value
$.ajax({
url: ‘/roles/’ + roleId, // assuming a REST API
method: ‘DELETE’
}).done(function() {
alert(‘Deleted role ‘ + roleId);
})
})
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *