2

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.

1
  • Go with the ajax solution if it's an array, and return json response()->json($data); Commented Oct 31, 2015 at 16:27

2 Answers 2

2

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

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

Comments

2

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>

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.