Hide Table of Contents
Adding a task

This example provides details on how to use a task. All tasks are asynchronous since they make HTTP requests to REST services. The query task is used, which shows tabular results but does not include a map.

Play with a live version of this sample in the ArcGIS API for JavaScript Sandbox. The sandbox is a live code editor that allows you to modify the sample's source and view the changes live.

The following is the HTML page in its entirety:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <!--The viewport meta tag is used to improve the presentation and behavior of the samples
      on iOS devices-->
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Query State Info without Map</title>

    <script src="https://js.arcgis.com/3.20/"></script>
    <script>
      require([
        "dojo/dom", "dojo/on",
        "esri/tasks/query", "esri/tasks/QueryTask", "dojo/domReady!"
      ], function (dom, on, Query, QueryTask) {

        var queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5");

        var query = new Query();
        query.returnGeometry = false;
        query.outFields = [
          "SQMI", "STATE_NAME", "STATE_FIPS", "SUB_REGION", "STATE_ABBR",
          "POP2000", "POP2007", "POP00_SQMI", "POP07_SQMI", "HOUSEHOLDS",
          "MALES", "FEMALES", "WHITE", "BLACK", "AMERI_ES", "ASIAN", "OTHER",
          "HISPANIC", "AGE_UNDER5", "AGE_5_17", "AGE_18_21", "AGE_22_29",
          "AGE_30_39", "AGE_40_49", "AGE_50_64", "AGE_65_UP"
        ];

        on(dom.byId("execute"), "click", execute);

        function execute () {
          query.text = dom.byId("stateName").value;
          queryTask.execute(query, showResults);
        }

        function showResults (results) {
          var resultItems = [];
          var resultCount = results.features.length;
          for (var i = 0; i < resultCount; i++) {
            var featureAttributes = results.features[i].attributes;
            for (var attr in featureAttributes) {
              resultItems.push("<b>" + attr + ":</b>  " + featureAttributes[attr] + "<br>");
            }
            resultItems.push("<br>");
          }
          dom.byId("info").innerHTML = resultItems.join("");
        }
      });
    </script>
  </head>

  <body>
    US state name :
    <input type="text" id="stateName" value="California">
    <input id="execute" type="button" value="Get Details">
    <br />
    <br />
    <div id="info" style="padding:5px; margin:5px; background-color:#eee;">
    </div>
  </body>
</html>

The following discussion assumes you are already familiar with the basic concepts of the JavaScript API and Dojo, and you understand the basic patterns of how the JavaScript API works within an HTML page. For more information, see Adding a map.

Scripts inside HTML HEAD

The scripts section inside HTML HEAD is where you write your functions that call the JavaScript API.

<script>

Reference the packages.

Since you are implementing a task, you need to reference the tasks package using require() statement. In this example, the esri/tasks package is referenced. For more information on what packages can be referenced, see About Dojo.

require(["esri/tasks/query"], function (Query) { /* code goes here */ });

Use the dojo/domReady! plugin.

The function block is where the query is built. First, a QueryTask named queryTask is initialized using the QueryTask constructor.

  • The value esri/tasks/QueryTask is the full reference to the QueryTask class. Class names are always capitalized.
  • The URL you see is the endpoint for a MapServer service named "ESRI_Census_USA". The query layer is layer "5", which references a states layer. This endpoint is a unique reference that you can generate using Services Directory.
function (dom, on, Query, QueryTask) {
  queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5");

Next, you need to build the query filter.

  • A Query named query is initialized using the Query constructor. This constructor does not include any parameters.
  • Depending on your application, you may want to have the geometry returned for each feature. If you do not want the geometry, you must set the property returnGeometry to false.
  • You need to include which fields you want displayed in the results using the property outFields. This list must use the actual field names rather than the alias names. You can display the field aliases in the results.
//build query filter
var query = new Query();
query.returnGeometry = false;
query.outFields = [
  "SQMI", "STATE_NAME", "STATE_FIPS", "SUB_REGION", "STATE_ABBR",
  "POP2000", "POP2007", "POP00_SQMI", "POP07_SQMI", "HOUSEHOLDS",
  "MALES", "FEMALES", "WHITE", "BLACK", "AMERI_ES", "ASIAN", "OTHER",
  "HISPANIC", "AGE_UNDER5", "AGE_5_17", "AGE_18_21", "AGE_22_29",
  "AGE_30_39", "AGE_40_49", "AGE_50_64", "AGE_65_UP"
];

Create a callback function.

The callback function execute is connected to the input button in the HTML page using the dojo/on class. In this example, a function named "execute" is called after a user types in a state name and clicks the "Get Details" button.

  • The state name is used as input text for the search. The property Query.text is short hand for a where clause using "like". This search is done only on the display field associated with the layer. This display field can be set in ArcMap document. If no display field is set, the default display field is the first text field. You can determine what the display field is for a layer in Services Directory.
  • Execute the query. You do this through the QueryTask.execute method. The inputs to the method are the Query and a reference to a function named showResults.
function execute(stateName) {
  query.text = stateName;
  //execute query
  queryTask.execute(query,showResults);
}

Create a function to show the results.

The showResults() function first parses the results based on the information received when the QueryTask was executed in the callback function. The results are passed into the showResults function in results, which is a FeatureSet object. A FeatureSet contains an array of Graphic features.

function showResults (results) {

In the next section of this function, the variable resultItems is populated with the field names and the field values contained in the results FeatureSet.

  • The outer for loop is repeated for each feature in the results FeatureSet. In this example, since only one state is processed, results contains only one Graphic, and the for loop is repeated only once.
  • The variable featureAttributes is assigned the attributes for each Graphic in the results FeatureSet.
  • The inner for loop is repeated for each attribute in featureAttributes. The field name (attr) and the field value (featureAttributes[attr]) are added to the resultItems array.
var resultItems = [];
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
  var featureAttributes = results.features[i].attributes;
  for (var attr in featureAttributes) {
    resultItems.push("<b>" + attr + ":</b>  " + featureAttributes[attr] + "<br>");
  }
  resultItems.push("<br>");
}

The next step in this function is to assign the value of resultItems as innerHTML, which allows text on an HTML page to be replaced with new text. In this example, dom.byId is used, which is similar to the document.getElementById(id) JavaScript function. This function searches and returns the first HTML element with the argument ID of "info". In this case, the text is written inside the HTML DIV with id="info".

dom.byId("info").innerHTML = resultItems.join("");

HTML BODY

The next section is the BODY section of the HTML page.

  • The first input provides a text box for a user to type in a state name. The default value is "California".
  • The second input is a button. The click event was attached when on(dom.byId("execute"), "click", execute); was executed in JavaScript. When a user clicks the button, the click event is invoked and calls the execute() function.
  • The DIV id "info" references the same variable set in the showResults() function.
<body>
  US state name :
  <input type="text" id="stateName" value="California">
  <input id="execute" type="button" value="Get Details">
  <br />
  <br />
  <div id="info" style="padding:5px; margin:5px; background-color:#eee;">
  </div>
</body>