CodeIgniter Forums
Variable passed to view as string, but cannot get js to interpret as a string? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Variable passed to view as string, but cannot get js to interpret as a string? (/showthread.php?tid=75404)



Variable passed to view as string, but cannot get js to interpret as a string? - nfoboy - 02-02-2020

Code from controller:


Code:
if($goodDates) {
            
    $data['start_date'] = $this->mapModel->getStartDate($theUser);
    $data['end_date'] = $this->mapModel->getEndDate($theUser);
    }
    
        $this->load->view('users/showMap', $data, FALSE);

which gets the variables into the View and I can see the strings when I am building the view
Code:
<?php
        if (isset($start_date)){
            ?>
            
            <p>a miracle <?php echo $start_date ?><br><?php echo $end_date ?> </p>
            <?php
        }
        ?>

But, when I try to assign to javascript variable, they are interpreted as numbers, not strings.

Code:
function initMap(){

<?php if ($end_date){ ?>
        
    var theStartDate =<?php echo $start_date ?>;
    var theEndDate = <?php echo $end_date ?>;

Above code gets theStartDate as 1993, NOT  2020-02-25, which is how it echos in the View's body section

I have not been able to successfully figure out how to php echo this as a string for use in the js section

Suggestions Welcome.


RE: Variable passed to view as string, but cannot get js to interpret as a string? - jreklund - 02-02-2020

You need to put quotes around it. Either " or '.

Code:
var theStartDate = "<?php echo $start_date ?>";



RE: Variable passed to view as string, but cannot get js to interpret as a string? - nfoboy - 02-02-2020

Thanks much. I definitely get confused about the order of timing for how these variables are accessed.... Smile