2

I would like to call an action method from within my plugin via ajax but I am always getting a 404 response.

I have a controller method that matches the ajax url:

jquery

$.ajax({
    'type': 'post',
    'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
    'cache': false,
    'data': data,
    'url': 'pluginHandle/checkStatus',
    'dataType': 'json',
    'timeout': 50000
}).done(function (response) {
    // Success
}).fail(function (error) {
   // Total fail.
});

MyPluginController.php

...

/**
 * Checks what the current status is RIGHT. NOW.
 *
 * @throws HttpException
 *
 */
public function actionCheckStatus()
{
    $this->requireAjaxRequest();

    $response = [
        'status' => 'open'
    ];

    $this->returnJson($response);
}

...

What am I doing wrong?

2 Answers 2

4

Make sure to check out the documentation on routing. Pay special attention to the part about action request(s).

In this example, I want to call a controller method via ajax on page load.

MyPluginController.php

...

/**
 * Checks what the current status is RIGHT. NOW.
 *
 * @throws HttpException
 *
 */
public function actionCheckStatus()
{
    $this->requireAjaxRequest();

    $response = [
        'status' => 'open'
    ];

    $this->returnJson($response);
}

...

jquery

$.ajax({
    'type': 'post',
    'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
    'cache': false,
    'data': data,
    'url': '/actions/pluginHandle/checkStatus',
    'dataType': 'json',
    'timeout': 50000
}).done(function (response) {
    // Success
}).fail(function (error) {
   // Total fail.
});

The key part to note is the url attribute in the ajax request. It is prepended with 'actions'. As you will note in the docs you can change 'actions' to whatever you want.

2

For Craft 3:

public function actionCheckStatus()
{
    $this->requireAcceptsJson();

    $response = [
        'status' => 'open'
    ];

    return $this->asJson($response);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.