3

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?

2 Answers 2

1

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}
Sign up to request clarification or add additional context in comments.

Comments

0

That's a perfectly good way to do it. Although you'll probably need quotes around the javascript url string:

var anUrl = '$urlFromPHP';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.