Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Ajax call to plugin

Started by Muut Archive 9 years ago · 6 replies · 1549 views
9 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

9 years ago

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

9 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.

9 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 :-) ]
9 years ago

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

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1322 9 years ago
Archive · by Muut Archive, 9 years ago
2 917 9 years ago
Archive · by Muut Archive, 9 years ago
2 4048 9 years ago
Archive · by Muut Archive, 9 years ago
1 2922 9 years ago
Archive · by Muut Archive, 9 years ago
3 1106 9 years ago