Home > OS >  Laravel send data from view to JavaScript file
Laravel send data from view to JavaScript file

Time:11-03

i want to send data that i get it from controller to javascript file that exist in public/js/maps.js how can i do this can any one help

my code Controller :

 public function index()
    {
        $userIp = "45.153.242.129";
        $locationData = \Location::get($userIp);
        
        return view('maps.index',[
            'location' => $locationData
          ]);
    }

view page:

<div id="world-map"></div>

maps.js

var handleVectorMap = function() {
    "use strict";
    if ($('#world-map').length !== 0) {
        $('#world-map').vectorMap({
            map: 'world_mill',
            scaleColors: [COLOR_GREY_DARKER, COLOR_GREY_LIGHTER],
            normalizeFunction: 'polynomial',
            hoverOpacity: 0.5,
            hoverColor: false,
            zoomOnScroll: true,
            markerStyle: {
                initial: {
                    fill: COLOR_RED,
                    stroke: 'transparent',
                    r: 3
                }
            },
            regionStyle: {
                initial: {
                    fill: COLOR_DARK_LIGHTER,
                    "fill-opacity": 1,
                    stroke: 'none',
                    "stroke-width": 0.4,
                    "stroke-opacity": 1
                },
                hover: {
                    "fill-opacity": 0.8
                },
                selected: {
                    fill: 'yellow'
                },
                selectedHover: { }
            },
            
            backgroundColor: 'transparent',
            markers: [
                {latLng: [41.90, 12.45], name: 'Vatican City'},
                {latLng: [43.73, 7.41], name: 'Monaco'},
            ]
        });
    }
};

so i want to display data in markers that exist in the javascript file.

CodePudding user response:

If it was in a single blade file, you could echo de json_encoded variables

<div id="world-map"></div>

<script>
const data = JSON.parse('{{ json_encode($data); }}');
</script>

If it's in a separate js file, you either need to get it through an ajax request request or store the data in an html element to query inside your js file.

Something like

<div id="world-map" data-maps='{{ json_encode($data) }}'></div>
const data = JSON.parse(document.getElementById('world-map').dataset.maps);

I think blade has a @json directive for just such a scenario.

CodePudding user response:

if you normaly using ( php echo name ). and now you want to call for name in your js code use (' value.name ') it will do the same like php echo

  • Related