简体   繁体   中英

how to access laravel controller data in imported javascript file

I use ajax to update a table based on the entries of the user.

 $('#user').change(function(){
var user= $("#user").val();
if (user !='None'){
  $.ajax({
      type: "GET",
      url: '/getUserAccounts/' + user,
      success: function (data) {
          $.each(opts, function(i, d) {
            console.log(d);
          });

      },
      error: function (data) {
          console.log('Error:', data);
      }
  });
}

});

I write the code in a <script> tag, all work fine. now i prefer to organize the javascript code in files and import them into my .blade.php file. the problem: the data passed from the controller is not recognized in my javascript file.

it's not possible to use controller data from a javascript file because they're not blade templates. What I usually do is have a hidden field on the page (or a meta header) that allows me to store the data I need and then I get the value I want from my JS files from those fields, example:

<input id="user_id" type="hidden" value="{{user_id}}">

In your javascript file:

var user_id = $("#user_id").val();

possible by creating pass value function

sample.js

function runCode(url) {
   // your code process
}

in blade.php

...
include sample.js here

<script>
   runCode('{{ $user_id }}');
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM