Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo php variable inside jQuery function

Tags:

jquery

php

joomla

i have this PHP variable set in joomla 2.5 template file

$datestart = date('Y-m-d g:i', strtotime("+1 week"));
$dateend = date('Y-m-d g:i', strtotime("+30 days"));

and when i echo this

<?php echo json_encode($datestart); ?> 

inside a php page it works. I'm trying to include this variable inside a jQuery function of the RS Form component

$formLayout .= "\n".'<script type="text/javascript" src="'.JURI::root(true).'/components/com_rsform/assets/calbs.js"></script>'."\n";

in the .js file i have

jQuery(function() {
jQuery("#datetimepicker").datetimepicker({
format: "dd MM yyyy - HH:ii P",
showMeridian: true,
autoclose: true,
startDate: <?php echo json_encode($datestart); ?>,
endDate: <?php echo json_encode($dateend); ?>,
minuteStep: 15,
pickerPosition: "bottom-left"

});
 });

But it's not working and shows syntax error for the php echo line. How can i solve this ?

like image 798
Kannan Naidu Avatar asked Jul 19 '26 07:07

Kannan Naidu


1 Answers

You have to assign the php values first to js variables in .php file

<script>
START_Date='<?php echo json_encode($datestart); ?>';
END_Date='<?php echo json_encode($dateend); ?>';

</script>

Now in your js file

jQuery(function() {
    jQuery("#datetimepicker").datetimepicker({
        format: "dd MM yyyy - HH:ii P",
        showMeridian: true,
        autoclose: true,
        startDate: START_Date,
        endDate: END_Date,
        minuteStep: 15,
        pickerPosition: "bottom-left"

    });
 });

OR include your js code in your php file then you can directly use php variables inside your js like this:

jQuery(function() {
    jQuery("#datetimepicker").datetimepicker({
        format: "dd MM yyyy - HH:ii P",
        showMeridian: true,
        autoclose: true,
        startDate: '<?php echo json_encode($datestart); ?>',
        endDate: '<?php echo json_encode($dateend); ?>',
        minuteStep: 15,
        pickerPosition: "bottom-left"

    });
});
like image 133
M Khalid Junaid Avatar answered Jul 20 '26 20:07

M Khalid Junaid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!