Ajax and Single Pages

Permalink
Hi, I want to make a Dashboard Single Page that uses Ajax to refresh some info. Does any one have some examples or insights on doing it? I though I saw a tutorial but don't find it now. I haven't done any Ajax with 5.7 and am not sure of what the best practices are.

Any help would be appreciated.

thanks
Peter

pvernaglia
 
hutman replied on at Permalink Reply
hutman
What we have done is to register a route in the on_start function of the package, then you can use that route for your ajax calls, and the route maps to a function in a file you create and store in the Src folder of the pacakage. Here is an example of the register line

Route::register('/unique-path', 'Concrete\Package\PackageName\Src\FileName::functionName');
pvernaglia replied on at Permalink Reply
pvernaglia
Thanks, I guess that's the first slice of the pie
Kiesel replied on at Permalink Reply
Or you can just add some ajax scripts in your single page view file like:

$.ajax({
            type: 'POST',
            dataType: 'json',
            url: '<? echo $this->action('action_youraction'); ?>',
            data: {'somedata':somedata},
            success: function(data) { 
              console.log(data);
            }
});


And it's counterpart action in your single page controller as an own method:

public function action_youraction($data){
    $result = "You said: " . $data; 
    echo json_encode(array("result" => $result));
    exit; 
  }
MrKDilkington replied on at Permalink Reply
MrKDilkington
Hi pvernaglia,

You can find a working AJAX example in the Simple Testimonials add-on by edbeeny.
https://www.concrete5.org/marketplace/addons/simple-testimonials...

In the add-on, there is a single page list of testimonials with sorting that is saved using AJAX.

There is an article on the topic written by the c5Hub team.
http://c5hub.com/learning/ajax-57-style/...

More working examples are in the Community Store add-on.

Example:
1. register the route to the method
community_store/controller.php
https://github.com/concrete5-community-store/community_store/blob/92...
2. create the method
community_store/src/CommunityStore/Cart/CartTotal.php
https://github.com/concrete5-community-store/community_store/blob/92...
3. setup the AJAX URL to use the route and method
community_store/js/community-store.js
https://github.com/concrete5-community-store/community_store/blob/92...
4. define the CARTURL
community_store/controller.php
https://github.com/concrete5-community-store/community_store/blob/e4...
4. call returnHeaderJS() using addFooterItem() in the blocks and single pages where you need the CARTURL