简体   繁体   中英

How to pass variable from controller to javascript?

im working on a laravel project. im trying to do auto-complete search box by retrieving data from the database. not sure how to foreach the collection and get it working in js

controller

$tag = DB::table('tags')->get(['title']);
view

//get each title for autocomplete
@foreach($tag as $key => $tag)
  <p>{{$tag->title}}</p>
@endforeach

<script>
    //im guessing im passing a tag collection right here??
    //so how do i foreach tag->title variable right here in js to get the title only?
    var tag = {!! json_encode($tag) !!};


    $(function() {

      var content = [
        { title: tag }
        // etc
      ];

      $('.ui.search')
      .search({
        source: content
       });  
   });
</script>

update: im using the pluck update my view

var tag = {!! json_encode($tag) !!};

    $(function() {

      var content = [
        { title: tag }
        // etc
      ];

      $('.ui.search')
      .search({
        source: content
       });  
   });

No need to json_encode

Just change your view file code as per below

<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>

<script>
    $(document).ready(function(){

        var tag = {!! $tag !!} ;

        console.log(tag); //here I console the tag data, you can use tag data as per your requirement

    });
</script>

UPDATE FINAL got it working yay

<script>
        $(document).ready(function(){

            var tag = {!! $tag !!} ;

            console.log(tag); //here I console the tag data, you can use tag data as per your requirement
            var content;
            var final="";

            tag.forEach(function (item, key) {
                //console.log(item);

                var str1= "[";
                var str2= "]";
                var str3= '{ "title": "';
                var str4= '"},';
                var str5= '"}';

                if (key==0) {
                    final = final + str1;
                }

                if (key+1!=tag.length) {
                    final= final+str3+item+str4;
                }
                else{
                    final= final+str3+item+str5+str2;
                }                

            });

            var obj = JSON.parse(final);

             console.log(obj);

            $('.ui.search')
            .search({
                source: obj
            })
            ;

        });

    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM