Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mantey's avatar

Passing Javascript variable to Laravel (PHP)

How can I pass the javascript variable name to the encrypt static method on Crypt

Screen-Shot-2019-10-04-at-1-26-26-PM

0 likes
8 replies
Nana's avatar

You'd probably have to use an ajax request for this. The javascript variable cannot be read by your PHP code. Besides, you can't call your PHP code in your script tags at runtime.

ashkan90's avatar

there's no way to do this without making a new request to your backend.

OneSeventeen's avatar

@nana and @ashkan90 are right, the PHP will be run first, with the results going to the visitor's browser, then after that the javascript that was sent to them will run.

You can send the variable "name" through an ajax request to a page, but then your Laravel web route will need to handle the request.

A good video I found on making ajax requests against Laravel is this one (which uses axios to make it even easier): https://laracasts.com/series/learn-vue-2-step-by-step/episodes/18

For yours, your javascript might look something like this:

var name = path.split('/').pop();
var fullPath = "{{ route('download.file', ':path')}}";
axios.get("/encrypt?value=" + name).then(response => fullPath = fullPath.replace(':path', response.data));

And your web.php routes file might look like this:

Route::get('/encrypt/{value}', function($value) {
  return Crypt::encrypt($value);
});

For me, to make axios work (I'm super new to this) I had to install Node and run "npm install" on the command line at my app root, then run "npm run watch" so it would build my .js file, then I added the <script src="/js/app.js"></script> tag into my blade template's header.

I hope that helps!

1 like
ftiersch's avatar

Wrong direction, @ltroya . He wants to pass JS to PHP, not the other way around :)

Please or to participate in this conversation.