1

Note: using the Laravel framework but the concept shouldn't be too different.

How would I go about passing my $data['method'] and $data['id] to javascript?

<div id="player" data-method="{{ $data['method'] }}" data-id="{{ $data['id'] }}"></div>

Data method and Data id are passed through a controller.

In javascript I've currently got

var method = "<?php echo $data-id[]>";
var id = "<?php echo $data-method[]>";

Which obviously don't work

1
  • 1
    Why echo $data-method[]? The [] is normally used to push data to an array. Commented May 14, 2014 at 9:04

4 Answers 4

4

To get the method:

var method = document.getElementById("player").getAttribute("data-method");

And to get the id:

var id = document.getElementById("player").getAttribute("data-id");
Sign up to request clarification or add additional context in comments.

Comments

1

In addition to @chris97ong answer, if you use jQuery, then you can use such constructions:

var method = $('#player').data('method');
var id = $('#player').data('id');

But if you want to paste id and method values directly to javascript, then use:

var method = "<?php echo $data['id']>";
var id = "<?php echo $data['method']>";

Exactly like in your own way.

Comments

1

You can pass array as

<?php
    $array = array("a","b","c","d");
    $json_str = json_encode($array);
?>
<a str='<?php echo $json_str; ?>' class="array_pass">Pass Value</a>

<script>
$(document).ready(function(e) {
    $(".array_pass").click(function() {
        var str = $(this).attr("str");
        var array = jQuery.parseJSON(str);
        alert(array[0]);
    });
});
</script>

Comments

0

Jeffrey Way provides a nice plugin to pass variables to JavaScript in your controller: https://github.com/laracasts/PHP-Vars-To-Js-Transformer

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.