AJAX in panel field plugin

Hi,
I’m trying to implement a panel field plugin and, specifically, to make an ajax request inside tha panel.

Here my code (a part of it):

Ajax request inside “site/fields/pluginName/assets/js/pluginName.js”

  $.ajax({
        url: "/panel/pages/pageName/ajax",
        type: 'POST',
        dataType: "json",
        success: function(data) {
            alert(data);
        }
    });

Route in config file:

c::set('routes', array(
  array(
    'pattern' => 'panel/pages/pageName/ajax',
    'method' => 'POST',
    'action' => function() {
      return response::json(array('some', 'json', 'stuff'));
    }
  )
));

The “data” in ajax success should be the json response, instead it’s an object like:

{"user":"admin","direction":"ltr","title":"...

I think it’a a path problem or maybe…I don’t know…

Thank

You can’t use the /panel namespace, because that uses the Panel index.php, which will not load and use custom routes.
Try using your own namespace like /pluginName/pageName/ajax.

Thanks @lukasbestle, I tried, but it doesn’t work.:disappointed:
Now it responds with a 404 error.

The routing code is in “site/config/config.php”.
I tried to insert the same ajax request in the public website and the routing answers correctly (‘some’, ‘json’, ‘stuff’).

In the ajax request in panel I tried both with “/pluginName/pageName/ajax” and with “pluginName/pageName/ajax” (starting slash). Nothing works, as if the routing doesn’t intercepts requests that start from the panel.

I tried the following code in a fresh installation of the starterkit and it worked just fine:

config.php

c::set('routes', array(
  array(
    'pattern' => 'pluginName/pages/pageName/ajax',
    'method' => 'POST',
    'action' => function() {
      return response::json(array('some', 'json', 'stuff'));
    }
  )
));

JavaScript code entered into browser console

$.ajax({
  url: "/pluginName/pages/pageName/ajax",
  type: 'POST',
  dataType: "json",
  success: function(data) {
    alert(data);
  }
});
2 Likes

Browser console inside a panel page?

Yes, after logging in on the dashboard and on a page edit page.
What you could try is to clear your browser cache.

Solved!

The problem was that I installed Kirby not in the root of the domain but in a “kb” folder so the right ajax url request in the panel has to be “/kb/pluginName/pages/pageName/ajax”

Shame on me. :blush:

Thanks @lukasbestle

5 posts were split to a new topic: Plugin toggle widget