0

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?

2 Answers 2

3

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:

  1. It is not using a side tag that could be confusing.
  2. The data you pass is included in the button, which means another button with its own 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.

Sign up to request clarification or add additional context in comments.

2 Comments

He can even use jQuery.data for that kind of tags.
Thanks @EricMartinez, I added your remark in the answer.
1

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;
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.