How can you call a function i a controller with javascript?

Is there a way to call a function in a controller with javascript?

Cheer, Maarten

What do you want to achieve?

I want to use parts of this framework.

After swipe i want to remove a post or mark a to do item as marked, this all i want to do on the frontend but protected.

So when a javascript function is trigged i want to trigger a function in the controller.

http://framework7.io/kitchen-sink-ios/

Go down and look for “Swipe To Delete”

This is what i’ve made so far.

https://ikzegja.com/app/contacts

this will be protected later. The first names are editible. The rest is dummy.

Cheers, Maarten

The best way would be to use a route that is then triggered by an AJAX request from the frontend.

Hello Lukas,

Thanks,

I’m new to routes and have no idea how to use them for triggering a action from a ajax script. Looked at the forum, still no clue…

I want to “remove” page or a post or todo" to make it hidden from the frontend with a swipe button.

the button wil trigger the ajax script.

AJAX

var request = new XMLHttpRequest(); 
request.open("POST", "ajax", true);
request.setRequestHeader('X-Requested-With','XMLHttpRequest');
request.send('removed=1')

Route

one of the problems is that i can’t use $page in router for some reason…

c::set('routes', array(
  array(
    'pattern' => '(:any)',
    'action'  => function() {
      $page->update(array('removed' => '1'));
      
    },
    'method' => 'POST'
  )
));

how can i make it work?

Cheers, Maarten

You should probably use something like this, otherwise your route won’t know what the current page is:

c::set('routes', array(
  array(
    'pattern' => '(:all)/remove',
    'action'  => function($uri) {
      // Check if the user has permission to remove the page (very important!!)
      ...
      
      $page = page($uri);
      if($page) {
        $page->update(array('removed' => '1'));
      } else {
        return response::error('Invalid URI', 404, ['uri' => $uri]);
      }
    },
    'method' => 'POST'
  )
));

You can then access the route from your JS code by adding /remove to the URL of the page.

PS: Do you know that you can also completely delete pages with $page->delete()? There are definitely use-cases for marking pages as deleted like in your example, but I just want to let you know.

1 Like