Reputation: 2422
I need to get the button id when the button is clicked---
This is my code for my button, to show dynamically data dynamically when the condition is true.
Twig:
{% for usr in userstats %}
{% if usr.condition == TRUE %}
<button type="submit" class="btn btn-success btn-xs myOnButton.onclick = function(event){alert(event.currentTarget.id);} myOnButton">Allow</button>
this is my ajax for my button ---
<script>
$(".myOnButton").on('click', function () {
if (confirm('{% trans %}Are you sure?{% endtrans %}')) {
$('body').addClass('load');
var url = '/hello/hello';
// Submit data via AJAX
var data = {};
$.ajax({
url: url,
type: 'POST',
success: function (data) {
// Redirect to view
url = '/hello';
location.href = url;
}
});
}
return false;
});
For being more clear- Suppose in one column we have (name:Dell, CompanyId:3001, Address- HelloDell, Phone-07555, condition:True) and in other column we have (name:Apple, CompanyId:5001, Address- HelloApple, Phone-07555, condition:True).
So how can I get the CompanyId when the button is clicked in the twig file?
Does someone know any solution for this problem?
Upvotes: 3
Views: 1717
Reputation: 1009
using plain JS (without frameworks) and asuming you have multiple buttons with the class myOnButton
you could easily do this:
var buttonClickHandler = function(e){
console.log(e.target.id);
}
var buttonList = document.getElementsByClassName('myOnButton');
buttonList.forEach(function(button){
button.addEventListener('click', buttonClickHandler);
});
EDIT1 & EDIT2:
using JQuery I assume corresponding code would look something like this:
$('.myOnButton').on('click', function(e){
var buttonId = e.currentTarget.id;
//start post request
$.post('my/path/to/service.php', {id:buttonId}, function(data, err){
//wait for response here
console.log("my data yippii", JSON.stringify(data));
})
});
PHP Part the service.php
would look something like this (I have to admit it's absolutely not my strength)
//retrieve id
id = $_POST['id'];
now that you got the ID you can verify it and start to SELECT on DB or something
hope this helped
Upvotes: 2