Stephen Stephen - 19 days ago 9
jQuery Question

How to call a controller action using Javascript $.get - Yii?

So, recently I've been trying to call a controller action via javascript

$.get
. I was suggested by a fellow Stack Overflow member to use

$.get("custom/balance", function(){ });


Where custom is the name of the controller that I am using and balance is
actionBalance()
—a function that I have declared inside of that controller. I have tried to do so but it seems that the function is not being called. I have placed intentional errors inside of that function so I am sure it is not being called via the
$.get
function.

previously, I had directed
$.get
to a file in assets like so

$.get("assets/balance.php, function() { });


This had worked perfectly.

Finally, here is the
actionBalance
that I have declared - is it possible that I need to then call that function? I'm not sure why custom/balance is not calling the action itself.

public function actionBalance() {

// Return a string
echo '7000';

}

Answer

I apologize for the previously incomplete answer which left you confused, as I assumed everyone would want to remove the index.php script name from the URL.

If you are using the default settings, yes, you should add the index.php?r= before the path. index.php is called the entry script in Yii. Other files are hidden/protected from the public in the protected folder.

To hide this entry script from the URL, please follow this tutorial on Yii's website: