-
Notifications
You must be signed in to change notification settings - Fork 12
Component API Multirequest
Using the /elation/multirequest facility, it's possible to call multiple server-side components with one HTTP call, and return all of their results in a single encapsulated response. This response can be a mixture of rendered HTML, JSON data, XML, etc. as requested by the frontend scripts.
Let's extend our Search example a bit. Say now we want to query our own database servers and also a third-party search API, and we want to show the results side by side. The files now look like this:
####components/search/search.php class Component_search extends Component { public function controller_search($args) { $query = any($args["query"], "default"); $vars["results_db"] = DataManager::query("db.posts.search#{$query}", "SELECT * FROM posts WHERE tags LIKE :query", array(":query" => "%{$query}%")); $vars["results_api"] = DataManager::query("rest.instasrch.posts#{$query}", array("query" => $query)); return $this->GetComponentResponse("./search.tpl", $vars); } public function controller_result($args) { $vars["result"] = $args["item"]; return $this->GetComponentResponse("./result.tpl", $vars); } }
####components/search/templates/search.tpl
####components/search/templates/result.tpl
{$result->contents|escape:html}
{$result->url|escape:html}If we wanted to make a request with a new query from the client side and update the contents of our two divs automatically, we can accomplish this end to end with a single JavaScript call:
elation.ajax.get("/elation/multirequest.ajax?requests=" + JSON.stringify([
{ component: "search", args: { query: "hello" }, assign: "search" },
{ component: "utils.list", args: { itemcomponent: "search.result", items: "$search.results_db.rows" }, target="results_db"},
{ component: "utils.list", args: { itemcomponent: "search.result", items: "$search.results_api.rows" }, target="results_api"}
]));
This will render two separate blocks of HTML, one for db results and the other for API results, and automatically inject them into the HTML using the specified target ids.