Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing dynamic data to javascript

It is good idea not to hardcode anything that may change in javascript. For example I want to have url generated by php.

I may write

echo "
<script ...>
    var anUrl = $urlFromPHP;
</script>";

and then:

<script ...>
    // some code
    $.ajax({ url: anUrl ... });
</script>";

Is there any better way to do it? Does anybody know if there is any built-in mechanism in yii framework?

like image 682
liysd Avatar asked Mar 23 '26 12:03

liysd


1 Answers

I personally like the conversion between php variables (arrays,...) to javascript object by json_encode. It is easy to use for complex arrays for example.

<?php 
// From manual:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);
?>
// results
{"a":1,"b":2,"c":3,"d":4,"e":5}
like image 141
Martin Vseticka Avatar answered Mar 26 '26 00:03

Martin Vseticka



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!