J_Strauton
J_Strauton

Reputation: 2418

Notify the controller of a button clicked in view

How do I notify the controller that the delete button was clicked?

MyController.php

public function actionUpdate($id)
{
    isset($_POST['del'])
    {
       // delete user.
    }
}

MyView.php

<?php
echo '<button type="button" class="btn btn-danger" name="deleteButton">Delete User</button>'; 
?>

This is what I tried:

    $('.deleteButton').click(function()
    {
        var clickBtnValue = $(this).val();
        var ajaxurl = Yii::app()->basePath . '/controllers/MyController.php';

        del =  {'action': clickBtnValue};
        $.post(ajaxurl, del, function (response) 
        {

            alert("action performed successfully");
        });
    });

But I can't receive the notice on the controller that the button was clicked.

Upvotes: 3

Views: 93

Answers (1)

Aleksei Akireikin
Aleksei Akireikin

Reputation: 1997

  1. It seems you use jQuery. $('.deleteButton') selects element by class, not by name. $('[name="deleteButton"]') should be used instead.
  2. You can't inject PHP code in JS this way. If your JS is written in a view, you should wrap the PHP code <?=Yii::app()->basePath ?>.
  3. Yii uses URL manager. It means URL does not equal controller file path. Build a URL from view <?=$this->createUrl('my/update', array('id' => $userId) ?>. Lear more about url management.

Upvotes: 2

Related Questions