M
M
Maybe_V2016-06-18 18:05:42
JavaScript
Maybe_V, 2016-06-18 18:05:42

How to properly implement ajax in yii2?

Need to be implemented jQuery.ajax in the project yii2 advanced.

The problem occurred when setting the jQuery property of the ajax method in the url.

<script>
    $(document).ready(function () {
        $(".category-div").click(function () {
            $.ajax({
                url: "../../test.php",
                dataType: "html",
                data: "id="+this.id,
                success: function(data){
                    $("#conteiner").html(data);
                },
                error: function () {
                    $("#conteiner").html("ERROR");
                }
            });
        });
    });
</script>


The problem occurs when urla file is installed that is not in webthe frontend.
That is, in the example I gave, everything works, but if you change the path for example to: url: /common/widget/views/test.phpor even /frontend/views/blog/test.php(provided that such a file is there, of course), it throws an error 404.

Why is this happening ? Why can't you link to files from any directory?

Moreover, everything works when you implement the file test.php:
<?php

?>
<!DOCTYPE html>
<html>
<head>
  <title>exa</title>
</head>
<body>

<?php

   return " <b>Получены параметры с сервера: </b> id = ".$_GET['id'];

?>
</body>
</html>


But when do this:
<?php

?>
<!DOCTYPE html>
<html>
<head>
  <title>exa</title>
</head>
<body>

<?php

   return " <b>Получены параметры с сервера: </b> id = ". Yii::$app->request->get('id');


?>
</body>
</html>


Throws an error:

GET portfolio/test.php?id=4 500 (Internal Server Error) jquery. js:9203


I ask for hints.
How to implement correctly ajaxin Yii2???

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2016-06-19
@webinar

1. Where did php come from at the end, if it is yii2 with its beautiful urlManager?
2.

/frontend/views/blog/test.php
it's probably a path, not a url.
3. Why not use YII2 tools
$this->registerJs('
$(".category-div").click(function () {
            $.ajax({
                url: "'.\yii\helpers\Url::toRoute(['blog/test','id'=>$someid]).'",
                dataType: "html",
                data: "id="+this.id,
                success: function(data){
                    $("#conteiner").html(data);
                },
                error: function () {
                    $("#conteiner").html("ERROR");
                }
            });
        });
');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question