When I was working on a project I faced a scenario where I should generate a URL in a controller method and then pass it into the AJAX
script in a blade view. So, lemme mimic this scenario with a charming example:
// web.php
use Illuminate\Support\Facades\Route;
Route::get('query', function () {
$route = route('users.search', ['created_at' => date('Y-m-d'), 'order' => 'DESC']);
return view('query', compact('route'));
});
Then we will use the `$route`
variable in the AJAX
script:
<script>
$('button[name=search]').click(function() {
$.ajax({
type: 'GET',
url: {{ $route }},
...
});
});
</script>
After that when we open the DevTool
and inspect the previous script tag we will figure out that the `
$route`
variable is malformed and the ampersand in that query string was rendered to &
instead of &
:
<script>
$('button[name=search]').click(function() {
$.ajax({
type: 'GET',
url: http://127.0.0.1:8000/search-users?created_at=2024-02-10&order=DESC,
...
});
});
</script>
If you click the Search button your Query string
will not be executed and to resolve the previous issue, you should use {!! !!} to render the variable correctly:
<script>
$('button[name=search]').click(function() {
$.ajax({
type: 'GET',
url: {!! $route !!},
...
});
});
</script>
It's safe to unescape the Query string
value in case you're who provided it because you will not ever inject a dangerous script but, you should mistrust the value that the application user provides because it may be a dangerous payload.
FINALLY, if you refresh the page you will notice that the variable is correctly rendered and therefore the Search button will work 🚀