Last active
December 11, 2015 21:06
-
-
Save bbatsche/e1321df3c742c3d26eaa to your computer and use it in GitHub Desktop.
Example of how to use JavaScript and a form to send a request using POST, rather than anchor tags and GET requests.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php foreach: ($parks as $parkInfo): ?> | |
<!-- ... --> | |
<td> | |
<!-- This is the button the user will click to remove an item --> | |
<button class="btn btn-danger btn-xs btn-delete" data-id="<?= $parkInfo['id']; ?>" data-name="<?= $parkInfo['name']; ?>"> | |
Delete | |
</button> | |
</td> | |
<!-- ... --> | |
<?php endforeach; ?> | |
<!-- This is a hidden form where we will feed the data for our request --> | |
<!-- Our JavaScript will pull out the park id, put it into the hidden field, and then submit this form --> | |
<form method="post" id="delete-form"> | |
<input type="hidden" name="id" id="delete-id"> | |
</form> | |
<script> | |
(function() { | |
"use strict"; | |
// Grab all the remove buttons and attached a click event listener to them | |
$(".btn-delete").click(function() { | |
// Pull out the id and name of the item we want to remove | |
var parkId = $(this).data("id"); | |
var parkName = $(this).data("name"); | |
// Make sure the user actually wanted to delete that park | |
if (confirm("Are you sure you want to delete " + parkName + "?")) { | |
// Put that ID into our hidden form field | |
$("#delete-id").val(parkId); | |
// Submit the form | |
$("#delete-form").submit(); | |
} | |
}); | |
})(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment