I'm trying to output a variable containing part of a URL into Javascript on my page. When I do this, it changes any &
into &
, which breaks the URL.
I've tried using str_replace
, html_entity_decode
, htmlspecialchars_decode
but the result was always same &
instead of &
.
How i can get it with &
instead of &
?
This is my controller:
//here we catch the query
public function index(Request $request)
{
$input = $request->getQueryString();
return view('lots.browse')->withInput($input);
}
// here we filter the ajax request
public function indexData(LotFilters $filters)
{
$lots = Lot::filter($filters);
return Datatables::eloquent($lots)->make(true);
}
This is my view:
<!-- Datatables -->
<script type="text/javascript">
$(document).ready(function(){
$('#table').DataTable({
searching: false,
processing: true,
serverSide: true,
ajax: '{{ url("/data") . "?" . html_entity_decode($input) }}',
columns: [
{ data: 'date', name: 'date' },
{ data: 'bid', name: 'bid' },
{ data: 'auction_name', name: 'auction_name' },
{ data: 'pics_urls', name: 'pics_urls' },
{ data: 'company', name: 'company' },
{ data: 'model_name_en', name: 'model_name_en' },
{ data: 'model_type_en', name: 'model_type_en' },
{ data: 'grade_en', name: 'grade_en' },
{ data: 'mileage_en', name: 'mileage_en' },
{ data: 'model_year_en', name: 'model_year_en' },
{ data: 'color_en', name: 'color_en' },
{ data: 'displacement', name: 'displacement' },
{ data: 'transmission_en', name: 'transmission_en' },
{ data: 'scores_en', name: 'scores_en' },
{ data: 'start_price_en', name: 'start_price_en' },
{ data: 'result_en', name: 'result_en' }
]
});
});
</script>
And this is the result:
When using a blade template, {{ $variable }}
will properly encode any characters that should not be placed directly in HTML. Since you're placing this variable in Javascript, you don't want this to happen.
The simplest solution is to disable HTML-encoding: {{!! $variable !!}}
.
But this is not the full solution. You need to ensure that the variable isn't blindly output, since if it contains a single quote, it will break your Javascript.
The full solution is to escape the string for single quotes:
{{!! addcslashes($input, "'") !!}}