3

I am new to Craft. I have done some ajax in the distant past. I have searched this forum and see lots of issues with ajax but it seems that there are a lot of different approaches. Craft docs have very little on Ajax.

I am wondering if there is a clear tutorial on doing ajax within craft. I have an address field set up and would like to click a button to retrieve all entries in a certain state and replace currently displayed data with the new data.

7

There is no real difference between a "normal" ajax request and an ajax request in Craft. You just leave the url blank, and insert an action parameter for your route. Craft 3 uses snake-case routes instead of camelCase. So when you want to access your plugin you would do.

action = "plugin-handle/controller-name/function-name

I full example as a CP request is

var data = {
    action: 'form-builder/setting/get-settings-for-site',
    siteId: siteId
};
// include csrf token
var tokenName = Craft.csrfTokenName;
data[tokenName] = Craft.csrfTokenValue;
$.ajax({
    type: "post",
    url: '',
    data: data,
    success: function (response) {
            ...
    },
    error: function (XMLHttpRequest, textStatus) {
        console.log("Status: " + textStatus);
    }
});

This would access my Form-builder plugin. The controller is SettingsController and the action actionGetSettingsForSite.

| improve this answer | |
  • Thank you Robin, you have been super helpful in getting me an understanding of Craft! – Eric Snyder Mar 12 '18 at 12:42
  • If you were able to create an ajax request you can mark the question as solved – Robin Schambach Mar 12 '18 at 13:05

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.