Reputation: 6136
I am developping a website with some serious Javascript involved and I have to use generated data from PHP in my JS code.
For example, to be able to use my page ID in JS, I proceed like this:
<input type="hidden" id="pageId" value="<?php echo $page->getId() ?>" />
<button id="runJs">RUN</button>
And in my javascript (with jQuery):
$(function() {
$('#runJs').click(function() {
var id = $('#pageId').val();
});
});
It works, but is there a cleaner way to do it?
Upvotes: 0
Views: 85
Reputation: 6136
Since HTML5, one can now add user-made attributes to any HTML tag as long as it starts with data-
.
In HTML5:
<button id="runJs" data-pageId="<?php echo $page->getId() ?>">RUN</button>
In JS:
$(function() {
$('#runJs').click(function() {
var id = $(this).attr('data-pageId');
});
});
Or, as said Eric Martinez in the comments, using jQuery:
var id = $(this).data('pageId');
Passing data this way is cleaner for two reasons:
data-XXX
can use the same JS function, even on the same page.Example
HTML:
<button data-value="5">Square it!</button>
<button data-value="7">Square it!</button>
<button data-value="12">Square it!</button>
JS:
$(function() {
$('button').click(function() {
var value = $(this).attr('data-value');
alert(value * value); // Shows 25, 49 or 144 depending of the button pressed.
});
});
The function doesn't know the button. The buttons don't even need an ID as long as JS is involved.
Upvotes: 3
Reputation: 1245
You can create variables inside the tag. Like this:
<script>
var pageId = '<?php echo $page->getId(); ?>';
</script>
Later in your script:
$(function() {
$('#runJs').click(function() {
var id = pageId;
});
});
Upvotes: 1