Reputation: 51
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
Upvotes: 1
Views: 2636
Reputation: 14523
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>
Upvotes: 1
Reputation: 5001
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.
Upvotes: 1
Reputation: 7060
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");
Upvotes: 4
Reputation: 1608
Jeffrey Way provides a nice plugin to pass variables to JavaScript in your controller: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
Upvotes: 0