4

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.

Eric Snyder
  • 531
  • 6
  • 14

1 Answers1

8

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.

Robin Schambach
  • 19,713
  • 1
  • 19
  • 44