Jump to content

How to get stdclass object to Javascript


Lassie

Recommended Posts

I am getting some varaibles from the databse and want to convert my array to javascript and use the input to make a map with markers.

I am cont get json encode to convert the stdclass object to a js object.

My second problem is how to accees the js vars to get an array of postcodes, lats and lng.

I have posted this topic before but became very confused so I am srtaring again.

I have commented where I think I have the problems.

Any suggestions welcome

<?php
                            //get town and county
                            //retrieve postcodes
                            //populate form
                            
                            //get town and county
                            $town=$_GET['town'];
                            $county=$_GET['county'];
                            global $wpdb;
                            $wpdb->show_errors();//debug
                            
                            $coords=array();
                            $results = $wpdb->get_results("SELECT postcode,latitude,longitude FROM uk_postcodes WHERE town = '$town'AND county='$county' ");// Get the postcode and lat and long
                            foreach ($results as $poi) {
                                    //echo $poi->{'postcode'},$poi->{'latitude'},$poi->{'longitude'} . '<br/>';
                                    
                                    $coords[]=$poi;
                                   
                                    //var_dump($coords);
                                   
                                }
                             
                                     echo "<pre>";
                                 print_r($coords);
                                    echo "</pre>"; 
                                //gives st class object
                                
                               //get the coords into javascript array
                               ?>
                            <script>
                                var coords = <?php echo json_encode($coords, true) ?>;
                                alert(coords);
                                //alert fails
                               
 
                            </script>
                            
                             <div id="map" style="width: 500px; height: 400px;"></div>
                            <script src="http://maps.google.com/maps/api/js?sensor=false" 
                            type="text/javascript"></script>
                            <script type="text/javascript">
                                //replace with coords, postcode, lat, lng
                            var locations = [
                            ['KT23', 51.28, -0.37, 4],
                            ['KT24', 51.26, -0.42, 5],
                            ['KT22', 51.30, -0.33, 5]
                                ]
                            var map = new google.maps.Map(document.getElementById('map'), {
                             zoom: 10,
                             center: new google.maps.LatLng(51.35, -0.26),
                            mapTypeId: google.maps.MapTypeId.ROADMAP
                            });
                            var infowindow = new google.maps.InfoWindow();

                             var marker, i;

                            for (i = 0; i < locations.length; i++) {  
                             marker = new google.maps.Marker({
                            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                            map: map
                                });

                            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                            return function() {
                            infowindow.setContent(locations[i][0]);
                            infowindow.open(map, marker);
                            }
                             })(marker, i));
                           }
                        </script> 
                                              
                            
                            
Link to comment
Share on other sites

You are getting that error because the PHP code is not outputting the json object, this results in an empty value being passed to JSON.parse and so you are getting the unexpected end of data error.

 

Are you sure $coords is defined and values are being set?

Link to comment
Share on other sites

Well, I set $coords=array(); and then ran the query and print r gives me the stdclass object as expected withthe right data.

I have put the following json encode in as a test.

$output = json_encode($coords);
                                
                                 echo "<pre>";
                                 print_r($output);
                                 echo "</pre>"; 

This gives

{"postcode":"AB10","latitude":"57.13","longitude":"-2.11"},{"postcode":"AB11","latitude":"57.13","longitude":"-2.09"},{"postcode":"AB12","latitude":"57.10","longitude":"-2.11"},{"postcode":"AB15","latitude":"57.13","longitude":"-2.16"},{"postcode":"AB16","latitude":"57.16","longitude":"-2.15"},{"postcode":"AB21","latitude":"57.21","longitude":"-2.20"},{"postcode":"AB22","latitude":"57.18","longitude":"-2.11"},{"postcode":"AB23","latitude":"57.21","longitude":"-2.08"},{"postcode":"AB25","latitude":"57.15","longitude":"-2.11"}]

I put this before the script with the json decode. Is this what I should expect and if so how to proceed?

Link to comment
Share on other sites

OK.

Just to be clear my (messey) code now is as follows before the google map

$coords=array();
                            $results = $wpdb->get_results("SELECT postcode,latitude,longitude FROM uk_postcodes WHERE town = '$town'AND county='$county' ");// Get the postcode and lat and long
                            foreach ($results as $poi) {
                                    //echo $poi->{'postcode'},$poi->{'latitude'},$poi->{'longitude'} . '<br/>';
                                    
                                    $coords[]=$poi;
                                   
                                    //var_dump($coords);
                                //$poi     = get_object_vars($poi);
                               // $postcode = $poi['postcode'];
                               // $Lat   = $poi['latitude'];
                                //$Lng  = $poi['longitude'];
                                //echo $Lat;
                                //echo $Lng;
                                   
                                }
                             
                                    // echo "<pre>";
                                 //print_r($coords);
                                    //echo "</pre>"; 
                                //gives st class object
                                
                               //get the coords into javascript array
                                $output = json_encode($coords);
                                
                                 echo "<pre>";
                                 print_r($output);
                                 echo "</pre>"; 
                                //gives st class object 
                                
                               ?>
                            <script>
                                
                                var coords = JSON.parse('<?php echo json_encode($coords) ?>');
                                alert(coords);
                                //alert fails
                               
 
                            </script>
                            

Now alert (coords) gives [object}.[Object] etc having removed  true ?

Link to comment
Share on other sites

I opened the developer console in chrome and it shows an array but not the values.

Array[9]0: Object1: Object2: Object3: Object4: Object5: Object6: Object7: Object8: Objectlength: 9__proto__: Array[0]

I have very little js expeireince so I am stuck. I want the values in an arry si can iterate through.

Any suggested approaches I can try, thanks.

Link to comment
Share on other sites

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

 

You use dot notation to access object properties in Javascript. Example:

var coords = [{"postcode":"AB10","latitude":"57.13","longitude":"-2.11"},{"postcode":"AB11","latitude":"57.13","longitude":"-2.09"}];

// coords[0].postcode
// coords[0].latitude

// coords[1].postcode
// coords[1].latitude
EDIT: You can loop over the array with something like:
var coords = [{"postcode":"AB10","latitude":"57.13","longitude":"-2.11"},{"postcode":"AB11","latitude":"57.13","longitude":"-2.09"}];

for (var i = 0; i < coords.length; i++) {
    document.write('Postcode: ');
    document.write(coords[i].postcode);
    document.write('<br />');
}
Will output:
Postcode: AB10
Postcode: AB11
Edited by scootstah
Link to comment
Share on other sites

Thanks.

So will

$output = json_encode($coords);
<script>
var coords = <?php echo $output?>;
</script>
  <div id="map" style="width: 500px; height: 400px;"></div>
                            <script src="http://maps.google.com/maps/api/js?sensor=false" 
                            type="text/javascript"></script>
                            <script type="text/javascript">
                                //replace with coords, postcode, lat, lng
                                var locations = [coords];
or (var i = 0; i < locations.length; i++) {
    document.write('Postcode: ');
    document.write(locations[i].postcode);
    document.write('<br />');
}

work. thanks

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.