1

I'm using a framework (yii2) and i'm adding a jQuery code inside my view. Like this:

$js = '$(document).ready(function(){
        $("#showmap").click(function(event){
          .....
          function success(position) {
            ...
            $.ajax({
                url : "../frontend/web/getContent.php",
                type: "POST",
                data: {success : "success", latitude : latitude, longitude : longitude},
                success: function (data){
                    var jsonmap = JSON.parse(data);
                    var address = jsonmap["results"]["0"]["formatted_address"];

                    $("#StreetName").val(address);
                }
            });
          }
        });
     });
';

$this->registerJs($js);

I have the file "getContent.php" in web directory. Where is the right place to put the file? What's the best method to do this code? Everything works great, but i don't know if this is the best way.

2 Answers 2

1

It's ok, as it's pointed out in Yii documentation

Just: - You don't need to close your code within $(document).ready, because Yii will do this for as default. - As best practice i'd suggest you to add a name to your block of code, so you can reuse it. - As best practice is always the best to put your code in external files so you can reuse it, and add it to bundle for being concatenated and minfied

Please, check the documentation link i pointed above, in section Registering inline scripts where is this explained.

Sign up to request clarification or add additional context in comments.

2 Comments

And the getContent.php what's the right place to put it and use in url?
@Juan.Queiroz lol, sorry... I don't think so... It would better to put that function inside an action, so you can call it as base-url/controller/action... I don't recomend the way you did it.
1

Just as a addition to the accepted comment for larger js and also css code I always useing this format

$script=<<<EOF
// my code
EOF;

With this I can use " and ' inside the js code and also easily use php variables to e.g. include an $url.

I only have to remember to escape all other strings which would be recognized as php variables but aren't. To escape just add a \ before the $ like \$no_php_variable.

Afterwards I use $this->registerJs($script, View::POS_READY,'my-button-handler'); as normal to register the script.

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.