• Resolved labyrinthman

    (@labyrinthman)


    I’m trying to get the data from the database to JavaScript but I’m getting
    [object Object] in the console.

    Here is my code:

    global $wpdb;
    $retrieve_data = $wpdb->get_row( "SELECT lat,lng FROM markers" );
    
    function object_to_array($retrieve_data)
    {
        if(is_array($retrieve_data) || is_object($retrieve_data))
        {
            $result = array();
     
            foreach($retrieve_data as $key => $value) {
                $result[$key] =object_to_array($value);
            }
     
            return $result;
        }
     
        return $retrieve_data;
    }
    
    $val=object_to_array($retrieve_data);
    
    <script type="text/javascript">
    	
    	  var myJsarray = <?php echo json_encode($val); ?>;
              console.log('data from database '+myJsarray);
    </script>
Viewing 3 replies - 1 through 3 (of 3 total)
  • javascript arrays are not like PHP arrays. If you use anything other than a number for a subscript, then it’s not an array, it’s an object.

    Thread Starter labyrinthman

    (@labyrinthman)

    Yes, I’m using a number, a float value.
    How can I make it possible to pass it from PHP to JS?

    Thread Starter labyrinthman

    (@labyrinthman)

    I have solved it, here is the code:

    First:

    global $wpdb;
        $retrieve_data = $wpdb->get_results( "SELECT * FROM markers" ); 
        $passedValues = array( 'retrieve_data' => $retrieve_data);
        wp_localize_script( 'spektrum_gmap.js', 'passed_object', $passedValues );

    Second, in js file:

    var myJsarray = passed_object.retrieve_data;
     for(i=0;i<myJsarray.length;i++){
    console.log("Lat Lng values"+myJsarray[i].lat +" "+myJsarray[i].lng);
      
    var lat = parseFloat(myJsarray[i].lat);
    var lng = parseFloat(myJsarray[i].lng);
    
    pos = new google.maps.LatLng(lat, lng);
    console.log("pos "+pos); 
    var marker=new google.maps.Marker({
    position:pos,
    map:map 
    });
    }
Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Values from database converted to JS shows as [object Object]’ is closed to new replies.