Reputation: 1059
Im trying to send a variable from a controller to a JavaScript, I have my controller, and I can send an array:
public function index()
{
$casa = new Casa(true);
$result = $casa->where(['show'=>true])->get();
return view('casa', array('casa' => $result));
}
If i go to my HTML and I make and echo:
<html>
<body>
<?php echo $casa ?>
</body>
</html>
I can show my array in the body, I was thinking about make an invisible element and get the array with document.getElementById().innerHTML, but I think this is not the best way.
Also, I think that I could make an Ajax petition sending a post and get the result, but I dont know if I can get my variable in a simpler way.
I tried to make and echo in Javascript and doesn´t work. some ideas?
Can I have 2 method post to get request in my controller? I already have one to get data from a form, and if I set the Ajax request I will have two post request. I would like have just one.
Upvotes: 2
Views: 3974
Reputation: 3978
You can simply get PHP
variable in JavaScript
like this:
<script>
var casa = '<?php echo $casa ?>';
</script>
you can use alert
to see the result in popup dialog too:
<script>
var casa = alert('<?php echo $casa ?>');
</script>
Upvotes: 2
Reputation: 1865
Jeffrey Way created a package for that. He also made a video explaining it in laracasts.com. The package can be found here: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
Upvotes: 2