{"id":1492,"date":"2022-08-30T15:16:59","date_gmt":"2022-08-30T15:16:59","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2013\/11\/23\/putting-php-variables-into-javascript-duplicate-collection-of-common-programming-errors\/"},"modified":"2022-08-30T15:16:59","modified_gmt":"2022-08-30T15:16:59","slug":"putting-php-variables-into-javascript-duplicate-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2022\/08\/30\/putting-php-variables-into-javascript-duplicate-collection-of-common-programming-errors\/","title":{"rendered":"Putting PHP variables into javascript [duplicate]-Collection of common programming errors"},"content":{"rendered":"<p>I&#8217;ve created a simple theme options page for my site. The options page contains three input fields. I can output the the fields by using get_option.<\/p>\n<p>The three fields are called using the following:<\/p>\n<pre><code>\n\n\n<\/code><\/pre>\n<p>These variables are for controlling the zoom level, the longitude and latitude of a map. I have a javascript file that renders the map using the google maps api. I&#8217;d like to put these variables into that javascript file. When I put the javascript into a php file and add these variables the map renders but I lose all the rest of my map functions which are considerable. Also I then have to call the script php in the header instead of using wp_enqueue_script in the functions file.<\/p>\n<p>Here is the map javascript:<\/p>\n<pre><code>var infowindow = new google.maps.InfoWindow();\nvar shadow = new google.maps.MarkerImage('\/wp-content\/themes\/re-aligned\/images\/shadow.png', new google.maps.Size(37, 34) );\n\n\nvar markers = [];\nvar categories = [\n    {\n        name: 'People',\n        slug: 'people',\n        url: 'marker-people.png'\n    }, {\n        name: 'Works',\n        slug: 'works',\n        url: 'marker-works.png'\n    }, {\n        name: 'Discourse',\n        slug: 'discourse',\n        url: 'marker-discourse.png'\n    }, {\n        name: 'Other',\n        slug: 'other',\n        url: 'marker.png'\n    }\n];\n\nString.prototype.endsWith = function(suffix) {\n    return this.indexOf(suffix, this.length - suffix.length) !== -1;\n};\n\nfunction initialize() {\n\n    jQuery('body').append(jQuery('<\/code><\/pre>\n<h2><code>Map Categories<\/code><\/h2>\n<pre>'));\n\n    \/\/ add checkboxes to toolbar\n    for (var i = 0; i &lt; categories.length; i++) {\n        jQuery('#toolbar').append(\n            jQuery('', {\n                type: 'checkbox',\n                id: 'tog-marker-'+categories[i].slug,\n                name: 'tog-marker-'+categories[i].slug,\n                class: 'squaredTwo',\n                value: i,\n                checked: true\n            })\n        );\n        jQuery('#toolbar').append(\n            categories[i].name\n        );\n    }\n\n    jQuery('#toolbar &gt; input[type=checkbox]').click(function() {\n        for(var i = 0; i &lt; markers.length; i++) {\n\n            if(markers[i].icon.url.endsWith(categories[jQuery(this).val()].url)) {\n                if(jQuery(this).is(':checked')) markers[i].setVisible(true);\n                else markers[i].setVisible(false);\n\n            }\n        }\n    });\n\n    \/\/ Create an array of styles.\n    var styles = [\n\n        {\n            \"featureType\": \"landscape.natural\",\n            \"stylers\": [\n                { \"color\": \"#ff412d\" },\n                { \"visibility\": \"on\" }\n            ]\n        },{\n            \"featureType\": \"administrative.land_parcel\",\n            \"stylers\": [\n                { \"visibility\": \"off\" }\n            ]\n        },{\n            \"featureType\": \"administrative.neighborhood\",\n            \"stylers\": [\n                { \"visibility\": \"off\" }\n            ]\n        },{\n            \"featureType\": \"administrative.province\",\n            \"stylers\": [\n                { \"visibility\": \"simplified\" }\n            ]\n        },{\n            \"featureType\": \"administrative.country\",\n            \"stylers\": [\n                { \"visibility\": \"on\" }\n            ]\n        },{\n            \"featureType\": \"water\",\n            \"stylers\": [\n                { \"color\": \"#ffebc5\" }\n            ]\n        },{\n            \"featureType\": \"road\",\n            \"stylers\": [\n                { \"visibility\": \"simplified\" },\n                { \"color\": \"#ffebc5\" }\n            ]\n        },{\n            \"featureType\": \"poi\",\n            \"stylers\": [\n                { \"visibility\": \"off\" }\n            ]\n        },{\n            \"featureType\": \"road.highway\",\n            \"stylers\": [\n                { \"visibility\": \"off\" }\n            ]\n        },{\n            \"featureType\": \"administrative.locality\",\n            \"stylers\": [\n                { \"visibility\": \"off\" }\n            ]\n        },{\n            \"featureType\": \"administrative.country\",\n            \"elementType\": \"geometry\",\n            \"stylers\": [\n                { \"visibility\": \"off\" }\n            ]\n        }\n    ];\n\n    \/\/ Create a new StyledMapType object, passing it the array of styles,\n    \/\/ as well as the name to be displayed on the map type control.\n    var styledMap = new google.maps.StyledMapType(styles,\n        {name: \"Styled Map\"});\n\n    \/\/ Create a map object, and include the MapTypeId to add\n    \/\/ to the map type control.\n    var mapOptions = {\n        zoom: ,\n        scrollwheel: true,\n        center: new google.maps.LatLng(, ),\n        mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style'],\n        mapTypeControl: true,\n        mapTypeControlOptions:  {\n            style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,\n            position: google.maps.ControlPosition.BOTTOM_CENTER\n        },\n        panControl: false,\n        panControlOptions: {\n            position: google.maps.ControlPosition.TOP_RIGHT\n        },\n        zoomControl: true,\n        zoomControlOptions: {\n            style: google.maps.ZoomControlStyle.LARGE,\n            position: google.maps.ControlPosition.LEFT_CENTER\n        },\n        scaleControl: false,\n        scaleControlOptions: {\n            position: google.maps.ControlPosition.LEFT_CENTER\n        },\n        streetViewControl: false,\n        streetViewControlOptions: {\n            position: google.maps.ControlPosition.LEFT_TOP\n        }\n    };\n    var map = new google.maps.Map(document.getElementById('map'), mapOptions);\n\n    var oms = new OverlappingMarkerSpiderfier(map);\n\n    \/\/Associate the styled map with the MapTypeId and set it to display.\n    map.mapTypes.set('map_style', styledMap);\n    map.setMapTypeId('map_style');\n\n    oms.addListener('click', function(marker, event) {\n        infowindow.setContent(marker.desc);\n        infowindow.open(map, marker);\n    });\n\n\n    for (var i = 0; i &lt; locations.length; i++) {\n        var marker = new google.maps.Marker({\n            position: locations[i].latlng,\n            desc: locations[i].info,\n            icon: locations[i].marker,\n            shadow: shadow,\n            map: map\n        });\n        oms.addMarker(marker);\n        markers.push(marker);\n    }\n\n}\n<\/pre>\n<p><code>How can i correctly output the variables into the javascript file?<\/code><\/p>\n<p><code><strong>UPDATE:<\/strong><\/code><\/p>\n<p><code>After taking on board the information about wp_localize_script I've done the following:<\/code><\/p>\n<p><code>I've put this in my functions.php<\/code><\/p>\n<pre><code><code>wp_enqueue_script( 'map-script' );\n    $object = array(\n        'zoom' =&gt; get_option('map_zoom'),\n        'longitude' =&gt; get_option('map_longitude'),\n        'latitude' =&gt; get_option('map_latitude'),\n    );  \nwp_localize_script('map-script', 'JSObject', $object);\n    } \n<\/code><\/code><\/pre>\n<p>and used JSObject.variable in my map javascript like so:<\/p>\n<pre><code>var mapOptions = {\n        zoom: JSObject.zoom,\n        scrollwheel: true,\n        center: new google.maps.LatLng(JSObject.latitude, JSObject.longitude),\n        mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style'],\n        mapTypeControl: true,\n        mapTypeControlOptions:  {\n            style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,\n            position: google.maps.ControlPosition.BOTTOM_CENTER\n        }\n<\/code><\/pre>\n<p>But that returns the error: <code>Uncaught Error: Invalid value for property : 9<\/code><\/p>\n<p>9 is the actual zoom variable so it appears to be working sort of&#8230;<\/p>\n<p id=\"rop\"><small>Originally posted 2013-11-23 09:50:56. <\/small><\/p>","protected":false},"excerpt":{"rendered":"<p>I&#8217;ve created a simple theme options page for my site. The options page contains three input fields. I can output the the fields by using get_option. The three fields are called using the following: These variables are for controlling the zoom level, the longitude and latitude of a map. I have a javascript file that [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-1492","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/1492","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=1492"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/1492\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=1492"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=1492"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=1492"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}