Reputation: 5920
I have the following link to make my ajax call in yii2:
echo Html::a('Load more','ajaxShowMoreProducts', [
'onclick'=>"console.log('Load more');
$.ajax({
type:'POST',
cache: false,
url: 'ajaxShowMoreProducts',
success: function(response) {
console.log('suc');
}
});return false;",
]);
Then I have an action in my SiteController:
/**
* @return string|\yii\web\Response
*/
public function actionAjaxShowMoreProducts() {
var_dump('in');die;
$params = [];
$productModel = new Product();
$params['products'] = $productModel->getAll();
$this->renderPartial('partialProductItem', $params);
}
However when I click the link,the correct controller action does not seem to be called. Its still calling site/index. Any ideas what I have to do to get this working? Have i forgotten some sort of annotation or maybe I have to define my new action somewhere?
When I look in the console, it looks correct: Request URL: http://localhost:8080/site/ajaxShowMoreProducts
Upvotes: 0
Views: 100
Reputation: 133370
In yii2 you should use the proper notation for action url (in url calling si not used the camelNotation but the words are separated by -
(minus)
echo Html::a('Load more','ajax-show-more-products', [
and in ajax url too
url: 'ajax-show-more-products',
or try using Url Helper
use yii\helpers\Url;
....
echo Html::a('Load more', Url::to(['/site/ajax-show-more-products']), [
'onclick'=>"console.log('Load more');
$.ajax({
type:'POST',
cache: false,
url: '" . Url::to(['/site/ajax-show-more-products']) . "',
success: function(response) {
console.log('suc');
}
});return false;",
]);
Upvotes: 2