jQuery App
Before you begin
Prior to starting this tutorial, you should have already completed the headless tutorial. This tutorial builds upon the concepts you learned in that tutorial as well as the web project and content type definitions discussed previously.
To get started with the jQuery tutorial you will need:
- Access to a Jahia system with appropriate permissions OR access to the free Jahia Cloud trial environment.
- Familiarity with javascript
What you will learn
In this tutorial, you will see how to build a simple javascript page pulling content from jContent.
This tutorial will introduce 3 topics:
- Introduction to XMLHttpRequest
- Executing graphQL calls with jQuery
- Displaying JSON objects with jQuery
Implementing GraphQL calls in jQuery
XMLhttprequest object
XMLHttpRequest is an API in the form of an object whose methods transfer data between a web browser and a web server
https://www.w3schools.com/xml/xml_http.asp
Jquery CLient Example
Access the prebuilt jQuery example of how to retrieve content from a Jahia instance. The example consists of 2 main javascript parts:
- Populating an XHR object in order to retrieve content from Jahia through a Graphql query
- Parsing the retrieved JSON object and generate HTML accordingly
Source code: https://github.com/Jahia/headless-tutorial-jsclient
GraphQL syntax to retrieve content
For the first GraphQL request, populate the XMLHttpRequest object before sending it. In this example there is a prebuilt function named ajax() that simplifies the syntax of that call:
https://github.com/Jahia/headless-tutorial-jsclient/blob/master/javascript/utils.js#L15
The call for this function is very similar to that jQuery ajax() call that is commonly used, but will instead set an XHR object and send it.
Ajax function call example :
ajax({
contentType: "application/json",
type:'POST',
url: "http://localhost:8080/modules/graphql",
method: "POST",
jsonData: getQuery(),
success: function(o) {...},
error:function(error) {...}
})
getQuery() builds the GraphQL query to be sent:
var getQuery = function(){
return {
query: "{" +
" jcr(workspace: LIVE) {" +
" nodeByPath(path: \"/sites/"+siteKey+"/contents\") {" +
" descendants(typesFilter: {types: [\"jntuto:tutorialItem\"]}) {"+
" nodes {"+
" title: property(name: \"jcr:title\"){value}" +
" body: property(name: \"body\"){value}" +
" image: property(name: \"image\") {"+
" path: refNode {"+
" path"+
" }" +
" }" +
" }" +
" }" +
" }" +
" }" +
" }"
}
}
Displaying JSON objects with jQuery
Next, display the retrieved content using the Bootstrap framework.
The utils.js file shows you how to embed the bootstrap framework with a bootstrap card appended to the HTML.
https://github.com/Jahia/headless-tutorial-jsclient/blob/master/javascript/utils.js#L69