Ajax call to plugin

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()) {

            $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

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

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.

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.
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) {}
});


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

I’m doing something similar in this plugin: https://github.com/flaviocopes/grav-plugin-api/blob/develop/api.php#L22-L55

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

@abzence You’re welcome :slight_smile: