Laravel - How to Pass a PHP Variable to a JavaScript Function from a Blade File

Using JavaScript to display Laravel's Variable

For more complex variable types like arrays your best bet is to convert it into JSON, echo that in your template and decode it in JavaScript. Like this:

var jobs = JSON.parse("{{ json_encode($jobs) }}");

Note that PHP has to run over this code to make it work. In this case you'd have to put it inside your Blade template. If you have your JavaScript code in one or more separate files (which is good!) you can just add an inline script tag to your template where you pass your variables. (Just make sure that it runs before the rest of your JavaScript code. Usually document.ready is the answer to that)

<script>
var jobs = JSON.parse("{{ json_encode($jobs) }}");
</script>

If you don't like the idea of doing it like this I suggest you fetch the data in a separate ajax request.

Use PHP variable as Javascript function parameters

Seems like you forgot about quotes, when you are passing strings into function.

<script>
$(document).ready(function () {
autoFill('{{ $dropDown }}', '{{ $emptyDropDown }}');
});
</script>

You can do it this way, but you shouldn't, because Laravel Blade do it for you itself.

<?php echo "<script> autoFill('".$dropDown."', '".$emptyDropDown."'); </script>"; ?>

How do I pass a variable from blade file to controller in laravel?

  1. You can't directly set a model's id like you're doing in the line $bid->id = $project_id;. Are you trying to set up a relationship? That should be more like $bid->project_id = $request->project_id;.
  2. Blade templates can't really pass things back to controllers, once they're in the browser your app is sort-of finished running. You need to create an HTML link/request on the page (like a form post request) that'll request the next thing from your app when the user clicks it.

If you want to create a button that creates a new bid for an existing project, you could do something like set up a form with a hidden field of 'project_id' that posts back to '/bids' which goes to the route 'bids.store'. You'll find 'project_id' under $request->project-id'.

Laravel pass value to javascript

You can make a script tag contain all your dynamic values, and make your file

/js/home.js

use it

like this

<script>
var appSettings = {message :"{{$message}}"};
</script>
<script src="/js/home.js"></script>

so inside home.js
you can access this value

alert(appSettings.message);


Related Topics



Leave a reply



Submit