Skip to main content
Home  › ... Razor

JavaScript API Tutorials

Tutorial HomeJavaScript

Use the sxc query(...) API to get Queries in JS

This page uses the sxc data API to query data from the backend using parameters and display it in a table with JavaScript.
In this tutorial you'll learn how to:

  • Create a $2sxc object using the current Module Id
  • Create a Query service using the .query(...).
  • Add Parameters to the .getAll(...), .getStream(...) and .getStreams(...) query methods through object or string

Note that this sample will run the query AuthorsWithBooks.

Output

  <button id="mod-@CmsContext.Module.Id-object" type="button" class="btn btn-primary">Get Query with parameters (object)</button>
  <button id="mod-@CmsContext.Module.Id-string" type="button" class="btn btn-primary">Get Query with parameters (string)</button>
  <button id="mod-@CmsContext.Module.Id-stream-params" type="button" class="btn btn-primary">Get Query Stream with parameters</button>
  <button id="mod-@CmsContext.Module.Id-streams-params" type="button" class="btn btn-primary">Get Query Streams with parameters</button>

   @* This tutorial uses turnOn, see turnOn tutorials *@
  @{
    var data = new {
      moduleId = CmsContext.Module.Id,
      demoAuthorId = demoAuthorId,
    };
  }
  
@Kit.Page.TurnOn("window.tutQueryParameters.init()", data: data)

  <script src="@CmsContext.View.Path/230-query-parameters.js"></script>

Source Code of 230-query-parameters.js

window.tutQueryParameters = {
  querySvc: null,
  demoAuthorId: 0,
  init: function({ moduleId, demoAuthorId }) {
    // Create a $2sxc object using the current Module Id
    const sxc = $2sxc(moduleId);
    this.querySvc = sxc.query('AuthorsWithBooks');
    this.demoAuthorId = demoAuthorId;

    // Attach click-handlers to button
    document.getElementById(`mod-${moduleId}-object`).onclick = () => this.queryWithObjectParams();
    document.getElementById(`mod-${moduleId}-string`).onclick = () => this.queryWithStringParams();
    document.getElementById(`mod-${moduleId}-stream-params`).onclick = () => this.queryStreamWithParams();
    document.getElementById(`mod-${moduleId}-streams-params`).onclick = () => this.queryStreamsWithParams();
  },

  queryWithObjectParams: function() {
    const queryParameters = {
      authorId: this.demoAuthorId,
      authorPageResults: 2,
      currentAuthorPage: 1
    };

    this.querySvc.getAll(queryParameters).then(data => {
      console.log("Get query with passing url parameters as object", data);
      alert('Got all - see console for details. \n \n' + JSON.stringify(data, null, 2));
    });
  },

  queryWithStringParams: function() {
    // For passing parameters as a string it's important to use the default query string structure (key=value seperated by a &)
    // See: https://en.wikipedia.org/wiki/Query_string#Structure
    const stringWithParameters = `authorId=${this.demoAuthorId}&authorPageResults=2&currentAuthorPage=1`;

    this.querySvc.getAll(stringWithParameters).then(data => {
      console.log("Get query with passing url parameters as string", data);
      alert('Got all - see console for details. \n \n' + JSON.stringify(data, null, 2));
    });
  },

  queryStreamWithParams: function() {
    const queryParameters = {
      authorId: this.demoAuthorId
    };

    this.querySvc.getStream('Current', queryParameters).then(data => {
      console.log("Get Query stream with passing url parameter", data);
      alert('Got all - see console for details. \n \n' + JSON.stringify(data, null, 2));
    });
  },

  queryStreamsWithParams: function() {
    const queryParameters = {
      authorId: this.demoAuthorId,
      authorPageResults: 2,
      currentAuthorPage: 1
    };

    this.querySvc.getStreams('Current,AuthorsByPage', queryParameters).then(data => {
      console.log("Get query streams with passing url parameter", data);
      alert('Got all - see console for details. \n \n' + JSON.stringify(data, null, 2));
    });
  }
}

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

@using ToSic.Razor.Blade;
@inherits Custom.Hybrid.Razor14
@{
  // Tell the page that we need the 2sxc Js APIs
  Kit.Page.Activate("2sxc.JsCore"); 
  var demoAuthorId = AsList(Data["RandomAuthor"]).FirstOrDefault().EntityId;
}
<!-- unimportant stuff, hidden -->


<div @Sys.PageParts.InfoWrapper()>
  @Html.Partial("../shared/DefaultInfoSection.cshtml")
  <div @Sys.PageParts.InfoIntro()>
      <h2>Use the sxc <code>query(...)</code> API to get Queries in JS</h2>
      <p>
        This page uses the sxc data API to query data from the backend using parameters and display it in a table with JavaScript.
        <br>
        In this tutorial you'll learn how to:
      </p>

      <ul>
        <li>
          Create a $2sxc object using the current Module Id
        </li>
        <li>
          Create a Query service using the <code>.query(...)</code>.
        </li>
        <li>
          Add Parameters to the <code>.getAll(...)</code>, <code>.getStream(...)</code> and <code>.getStreams(...)</code> query methods through object or string
        </li>
      </ul>
      <p>
        Note that this sample will run the query <code>AuthorsWithBooks</code>.
      </p>
    </div>
  </div>

  <button id="mod-@CmsContext.Module.Id-object" type="button" class="btn btn-primary">Get Query with parameters (object)</button>
  <button id="mod-@CmsContext.Module.Id-string" type="button" class="btn btn-primary">Get Query with parameters (string)</button>
  <button id="mod-@CmsContext.Module.Id-stream-params" type="button" class="btn btn-primary">Get Query Stream with parameters</button>
  <button id="mod-@CmsContext.Module.Id-streams-params" type="button" class="btn btn-primary">Get Query Streams with parameters</button>

   @* This tutorial uses turnOn, see turnOn tutorials *@
  @{
    var data = new {
      moduleId = CmsContext.Module.Id,
      demoAuthorId = demoAuthorId,
    };
  }
  
@Kit.Page.TurnOn("window.tutQueryParameters.init()", data: data)

  <script src="@CmsContext.View.Path/230-query-parameters.js"></script>



@* Footer *@
@Html.Partial("../Shared/Layout/FooterWithSource.cshtml", new { Sys = Sys })