Skip to content
● Meet Grav Guard: keep every Grav site you run secure and up to date, all from one place. Free for up to 3 sites. Read more →

Ajax call to plugin

Started by Muut Archive 10 years ago · 6 replies · 1817 views
10 years ago

Hello,

I need some help to achieve some ajax into a plugin.
I'm working on a kind of cart for asking quote. I'd like to do some ajax inside the plugin.

Into the cart, when changing quantity for example on my checkout page, i need to call a file (ajax.php) to update information into session, compute new total and so.

how could i achieve this indo a plugin ? I try to configure something :

if ($this->ajax_url && $this->ajax_url == $uri->path()) {

PHP
            $this->enable([
                'onPageFallBackUrl' => ['ajaxCall', 0]
            ]);
        }

But i don't know what event to call without displaying a page.

Any help will be appreciate.

Thanks for all

10 years ago

I think i get it :-). Back here if i need more help.

10 years ago

Could you share some example on how you made this work?
I've been trying similar things and I'm sure others have too. Thank you.

10 years ago

Hello,

Find below how i achieve this.

  1. define my ajax_url into my plugin
  2. add an action field in my POST. Into the cart_utils.php, get a switch that call a function regarding the $_POST['action'] field.
PHP
public function onPagesInitialized(){
         $uri = $this->grav['uri'];
         $this->ajax_url = $this->config->get('plugins.mycart.urls.ajax_url'); 
         require_once("classes/cart_utils.php");
         $helper = new Cartutils();

         if ($this->ajax_url && $this->ajax_url == $uri->path()) {
                    if(isset($_POST['action'])){
                        $helper->switch();
                        exit();
                    }else{
                        exit();
                    }
            }else{ [...]}
    }
--- 

The important point is the exit() !!!! This avoid any display of Grav.

And then in your html.twig you could do ajax call like :

$.ajax({
type:'post',
url:'/ajax_url',
data:{},
success:function(response) {},
error: function(response) {}
});

TXT


Hope that could help. [Sure there is a better way :-) ]
10 years ago

Thank you! This got me in the right direction for my own project.

Suggested topics

Topic Participants Replies Views Activity
Archive · by Muut Archive, 10 years ago
1 672 1 week ago
Archive · by Deleted User, 9 years ago
0 3042 9 years ago
Archive · by Muut Archive, 9 years ago
2 1983 9 years ago
Archive · by Muut Archive, 9 years ago
2 5336 9 years ago
Archive · by Muut Archive, 9 years ago
1 4134 9 years ago