MeliDev
MeliDev

Reputation: 87

Display laravel variable using javascript

when i try dd($conv) the data are there, but I still can't display them inside the script. Anyone know whats the problem, I have tried many ways but they doesn't seem to work.

  <h4>{{$row->transcript_text}}</h4>
    <?php $conv = json_encode($row->transcript_text); ?>
    <script type="text/javascript">
        function splitArray() {
            var myStr = <?php echo $conv; ?>;
            var strArray = myStr.split(/(?= \| \d)/);

            // Display array values on page
            for (var i = 0; i < strArray.length; i++) {
                $("body").addClass('col-lg-offset-1').append("<h4>" + strArray[i] + "</h4>");
            })
        }
        splitArray();
    </script>

Upvotes: 0

Views: 268

Answers (1)

ValLeNain
ValLeNain

Reputation: 2304

I don't know which version of Laravel you're using but the recommended way to embed plain PHP in your HTML templates is with the @php notation (cf doc). Anyway, that's something I'd try to avoid. Instead, Laravel blade has native ways of doing what you're trying to do.

@if(! empty($history))
    @foreach($history as $row)
    <script type="text/javascript">
        function splitArray() {
            var myStr = JSON.parse("{{json_encode($row->transcript_text) }}");
            var strArray = myStr.split(" | 0");

            // Display array values on page
            for (var i = 0; i < strArray.length; i++) {
                $("body").addClass('col-lg-offset-1').append("<h4>" + strArray[i] + "</h4>");
            }
        }
    </script>
    <body onload="splitArray()" style="color: lime">
    </body>
    @endforeach

Upvotes: 1

Related Questions