Juan.Queiroz
Juan.Queiroz

Reputation: 227

jQuery code inside MVC

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.

Upvotes: 1

Views: 78

Answers (2)

BHoft
BHoft

Reputation: 1663

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.

Upvotes: 1

Leandro Gatti
Leandro Gatti

Reputation: 97

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.

Upvotes: 1

Related Questions