Home > Mobile >  Passing JSON to Javascript in Laravel – but JS is converting the JSON to HTML Entities
Passing JSON to Javascript in Laravel – but JS is converting the JSON to HTML Entities

Time:05-10

In my Laravel controller, I am creating a multidimensional associative array:

$trendChart = Array (
    "series" => Array (
        "data" => Array(1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5)
    ),
    "xaxis" => Array (
        "categories" => Array ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"),
    ),
    "chart" => Array (
        "type" => "line",
        "height" => 350,
    ),
    "stroke" => Array (
        "curve" => "smooth",
    ),
    "dataLabels" => Array (
        "enabled" => false,
    ),
    "fill" => Array (
        "colors" => Array ("#006ba6", "#f23f2b", "#f3f3f3")
    ),
    "annotations" => Array (
        "yaxis" => Array (
            "y" => 4.8,
            "borderColor" => "rgba(155, 199, 0, 1)",
            "borderWidth" => 3,
            "label" => Array(
                "borderColor" => "rgba(155, 199, 0, 1)",
                "style" => Array(
                    "color" => "#fff",
                    "background" => "rgba(155, 199, 0, 1)",
                ),
                "text" => "Ideal Average",
            ),
        ),
    ),
);

I then encode it into JSON, with:

$defaultChartOptions = json_encode($trendChart);

And then I pass $defaultChartOptions into my view:

return view('myview')->with(['defaultChartOptions' => $defaultChartOptions]);

Inside my view, I have the following JS:

var chartOptions = JSON.parse({{$defaultChartOptions}});

For the record, I have also attempted this without the JSON.parse command. Either way, by the time it gets passed to the JS, all of the quote marks have been converted into HTML entities. To view the page source, it looks like this:

var chartOptions = {"series":{"data":[1,1,2,2,3,3,3,3,4,4,4,5]},"xaxis":{"categories":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},"chart":{"type":"line","height":350},"stroke":{"curve":"smooth"},"dataLabels":{"enabled":false},"fill":{"colors":["#006ba6","#f23f2b","#f3f3f3"]},"annotations":{"yaxis":{"y":3,"borderColor":"rgba(229, 78, 78, .65)","borderWidth":3,"label":{"borderColor":"rgba(229, 78, 78, 1)","style":{"color":"#fff","background":"rgba(229, 78, 78, 1)"},"text":"Your Average"}}}}

What am I missing here?

CodePudding user response:

Instead, doing

var chartOptions = JSON.parse({{$defaultChartOptions}});

do:

This will prevent the data to be escaped

var chartOptions = {!! ($defaultChartOptions) !!};

CodePudding user response:

You can simply get that by changing:

var chartOptions = JSON.parse({{$defaultChartOptions}});

to:

var chartOptions = {!! ($defaultChartOptions) !!};

and your problem will be solved.

  • Related