Fetch data from MySQL inside .js file [duplicate] - javascript

This question already has answers here:
connect AngularJS to mysql using my PHP service?
(2 answers)
Closed 8 years ago.
I am looking for a solution for almost 3 days but i can't figure it out. This is my problem:
I have file called: index.php
<html>
<head>
<title>AngularJS-FlowChart</title>
<!--
LiveReload support.
http://livereload.com/
-->
<script src="http://localhost:35729/livereload.js?snipver=1"></script>
</head>
<body
ng-app="app"
ng-controller="AppCtrl"
mouse-capture
ng-keydown="keyDown($event)"
ng-keyup="keyUp($event)"
>
<div style="width: 100%; overflow: hidden;">
<!--<div style="width: 600px; float: left;">
<textarea
style="width: 100%; height: 100%;"
chart-json-edit
view-model="chartViewModel"
>
</textarea>
</div>-->
<div style="margin-left: 0px;">
<button
ng-click="addNewNode()"
title="Add a new node to the chart"
>
Add Node
</button>
<button
ng-click="addNewInputConnector()"
ng-disabled="chartViewModel.getSelectedNodes().length == 0"
title="Add a new input connector to the selected node"
>
Add Input Connector
</button>
<button
ng-click="addNewOutputConnector()"
ng-disabled="chartViewModel.getSelectedNodes().length == 0"
title="Add a new output connector to the selected node"
>
Add Output Connector
</button>
<button
ng-click="deleteSelected()"
ng-disabled="chartViewModel.getSelectedNodes().length == 0 && chartViewModel.getSelectedConnections().length == 0"
title="Delete selected nodes and connections"
>
Delete Selected
</button>
<!--
This custom element defines the flowchart.
-->
<flow-chart
style="margin: 5px; width: 40%; height: 70%; float: right"
chart="chartViewModel"
>
</flow-chart>
<flow-chart
style="margin: 5px; width: 40%; height: 70%; float: left"
chart="chartViewModel"
>
</flow-chart>
</div>
</div>
<link rel="stylesheet" type="text/css" href="app.css">
<!-- Library code. -->
<script src="lib/jquery-2.0.2.js" type="text/javascript"></script>
<script src="lib/angular.js" type="text/javascript"></script>
<!-- Flowchart code. -->
<script src="debug.js" type="text/javascript"></script>
<script src="flowchart/svg_class.js" type="text/javascript"></script>
<script src="flowchart/mouse_capture_service.js" type="text/javascript"></script>
<script src="flowchart/dragging_service.js" type="text/javascript"></script>
<script src="flowchart/flowchart_viewmodel.js" type="text/javascript"></script>
<script src="flowchart/flowchart_directive.js" type="text/javascript"></script>
<!-- App code. -->
<script src="app.js" type="text/javascript"></script>
</body>
</html>
And I have another file called: app.js
//
// Define the 'app' module.
//
angular.module('app', ['flowChart', ])
//
// Simple service to create a prompt.
//
.factory('prompt', function () {
/* Uncomment the following to test that the prompt service is working as expected.
return function () {
return "Test!";
}
*/
// Return the browsers prompt function.
return prompt;
})
//
// Application controller.
//
.controller('AppCtrl', ['$scope', 'prompt', function AppCtrl ($scope, prompt) {
//
// Code for the delete key.
//
var deleteKeyCode = 46;
//
// Code for control key.
//
var ctrlKeyCode = 65;
//
// Set to true when the ctrl key is down.
//
var ctrlDown = false;
//
// Code for A key.
//
var aKeyCode = 17;
//
// Code for esc key.
//
var escKeyCode = 27;
//
// Selects the next node id.
//
var nextNodeID = 10;
//
// Setup the data-model for the chart.
//
var chartDataModel = {};
//
// Event handler for key-down on the flowchart.
//
$scope.keyDown = function (evt) {
if (evt.keyCode === ctrlKeyCode) {
ctrlDown = true;
evt.stopPropagation();
evt.preventDefault();
}
};
//
// Event handler for key-up on the flowchart.
//
$scope.keyUp = function (evt) {
if (evt.keyCode === deleteKeyCode) {
//
// Delete key.
//
$scope.chartViewModel.deleteSelected();
}
if (evt.keyCode == aKeyCode && ctrlDown) {
//
// Ctrl + A
//
$scope.chartViewModel.selectAll();
}
if (evt.keyCode == escKeyCode) {
// Escape.
$scope.chartViewModel.deselectAll();
}
if (evt.keyCode === ctrlKeyCode) {
ctrlDown = false;
evt.stopPropagation();
evt.preventDefault();
}
};
//
// Add a new node to the chart.
//
$scope.addNewNode = function () {
var nodeName = prompt("Enter new node!", "New node");
if (!nodeName) {
return;
}
//
// Template for a new node.
//
var newNodeDataModel = {
name: nodeName,
id: nextNodeID++,
x: 50,
y: 50
};
$scope.chartViewModel.addNode(newNodeDataModel);
};
//
// Add an input connector to selected nodes.
//
$scope.addNewInputConnector = function () {
var connectorName = prompt("Enter a connector name:");
if (confirm(connectorName)) {
var selectedNodes = $scope.chartViewModel.getSelectedNodes();
for (var i = 0; i < selectedNodes.length; ++i) {
var node = selectedNodes[i];
node.addInputConnector({
name: connectorName
});
}
} else return;
};
//
// Add an output connector to selected nodes.
//
$scope.addNewOutputConnector = function () {
var connectorName = prompt("Enter a connector name:");
if (confirm(connectorName)) {
var selectedNodes = $scope.chartViewModel.getSelectedNodes();
for (var i = 0; i < selectedNodes.length; ++i) {
var node = selectedNodes[i];
node.addOutputConnector({
name: connectorName,
});
}
} else return;
};
//
// Delete selected nodes and connections.
//
$scope.deleteSelected = function () {
$scope.chartViewModel.deleteSelected();
};
//
// Create the view-model for the chart and attach to the scope.
//
$scope.chartViewModel = new flowchart.ChartViewModel(chartDataModel);
}])
;
The thing I want to achieve is to read data from MySQL and use that same data inside app.js file. I'd really need any help please.
I was reading all articles about this thema on first 5 google pages but without any success. I tried all sorts of "tutorials" but i could find the solution.

Use jQuerys AJAX function to send data to a PHP Service:
$.ajax({
type: 'POST',
url: path + '/php/yourService.php',
data: 'var=' + var,
success: function (response) {
// Do smth with the response
}
});
In your PHP Service read out data of the database:
// connect to your database first
$username = $_POST["var"];
$sql="SELECT * FROM users WHERE anything = '$var'";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_array($result)){
return $row["variable"];
}
Should do the trick. Don´t matter if angular or not. The returned data is accessibly through the response variable in ajax onSuccess function. Hope this helps

Related

How to load search data on load?

I received this code from another user in this forum.
Issue: As seen in the below screenshot, the search results (or data) starts to appear when you click or start typing in the search box or else only the search box loads without the data.
Requirement: I want to display the results (or data) as the page loads.
The code is given below
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
   
<style>
.nav-link {
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<ul class="nav nav-tabs">
<li class="nav-item">
<div class="nav-link"id="search-link">Search</div>
</li>
</ul>
<div id="app"></div>
<!-- Content here -->
</div>
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script>
var data;
function loadView(options){
var id = typeof options.id === "undefined" ? "app" : options.id;
var cb = typeof options.callback === "undefined" ? function(){} : options.callback;
google.script.run.withSuccessHandler(function(html){
document.getElementById("app").innerHTML = html;
typeof options.params === "undefined" ? cb() : cb(options.params);
})[options.func]();
}
function setDataForSearch(){
google.script.run.withSuccessHandler(function(dataReturned){
data = dataReturned.slice();
}).getDataForSearch();
}
function search(){
var searchinput = document.getElementById("searchinput").value.toString().toLowerCase().trim();
var searchWords = searchinput.split(/\s+/);
var searchColumns = [0,1,2,3,4,5,6,7];
// and or
var resultsArray = data.filter(function(r){
return searchWords.every(function(word){
return searchColumns.some(function(colIndex){
return r[colIndex].toString().toLowerCase().indexOf(word) !== -1
});
});
});
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
searchResultsBox.innerHTML = "";
resultsArray.forEach(function(r){
var tr = template.cloneNode(true);
var hinmokuColumn = tr.querySelector(".hinmoku");
var buhinCodeuColumn = tr.querySelector(".buhinCode");
var buhinNameColumn = tr.querySelector(".buhinName");
var hitsuyoColumn = tr.querySelector(".hitsuyo");
var genkaColumn = tr.querySelector(".genka");
var kobaiColumn = tr.querySelector(".kobai");
var sagakuColumn = tr.querySelector(".sagaku");
var kenshoColumn = tr.querySelector(".kensho");
hinmokuColumn.textContent = r[0];
buhinCodeuColumn.textContent = r[1];
buhinNameColumn.textContent = r[2];
hitsuyoColumn.textContent = r[3];
genkaColumn.textContent = r[4];
kobaiColumn.textContent = r[5];
sagakuColumn.textContent = r[6];
kenshoColumn.textContent = r[7];
searchResultsBox.appendChild(tr);
});
}
function loadSearchView(){
loadView({func:"loadSearchView", callback: setDataForSearch});
}
window.addEventListener("load", loadSearchView);
function inputEventHandler(e){
if (e.target.matches("#searchinput")){
search();
}
}
document.getElementById("app").addEventListener("input",inputEventHandler);
document.getElementById("app").addEventListener("click",inputEventHandler);
</script>
</body>
</html>
server-side code
function getDataForSearch(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("TableData");
return ws.getRange(2, 1, ws.getLastRow(),8).getValues();
}
I need to know what modification needs to be done in the code?
I tried document.getElementById("app").addEventListener("load",inputEventHandler);
but it didn't work.
is there any other event listeners available that will load the search results (or data) (without taking any action on the site, i mean without clicking or typing in the search box)?
Thanks in advance.
Edit: loadsearchview function file code
function loadSearchView(){
return loadPartialHTML_("search");
}
You could use addEventListener with DOMContentLoaded to call a function when all the HTML is loaded and the DOM tree is built. For your particular situation, here's how I managed:
First I need to load data into data variable and call the loadSearchView() function when the page loads:
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", function () {
google.script.run.withSuccessHandler(function (r) {
data = r;
loadSearchView();
}).getDataForSearch();
});
} else {
google.script.run.withSuccessHandler(function (r) {
data = r;
loadSearchView();
}).getDataForSearch();
}
Then I need to load the search view, but instead of calling setDataForSearch, I implemented another function to call functions after this view is loaded. This might be useful if you want to call more than one function after the searchView loads. So basically the code would be like this:
function loadSearchView() {
loadView({ func: "loadSearchView", callback: afterSearchViewLoads });
}
function afterSearchViewLoads(){
loadDataWhenPageLoads();
}
function loadDataWhenPageLoads(){
var resultArray = data;
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
searchResultsBox.innerHTML = "";
resultsArray.forEach(function (r) {
var tr = template.cloneNode(true);
var hinmokuColumn = tr.querySelector(".hinmoku");
var buhinCodeuColumn = tr.querySelector(".buhinCode");
var buhinNameColumn = tr.querySelector(".buhinName");
var hitsuyoColumn = tr.querySelector(".hitsuyo");
var genkaColumn = tr.querySelector(".genka");
var kobaiColumn = tr.querySelector(".kobai");
var sagakuColumn = tr.querySelector(".sagaku");
var kenshoColumn = tr.querySelector(".kensho");
hinmokuColumn.textContent = r[0];
buhinCodeuColumn.textContent = r[1];
buhinNameColumn.textContent = r[2];
hitsuyoColumn.textContent = r[3];
genkaColumn.textContent = r[4];
kobaiColumn.textContent = r[5];
sagakuColumn.textContent = r[6];
kenshoColumn.textContent = r[7];
searchResultsBox.appendChild(tr);
});
}
Hope this can solve your problem!
AddEventListener when you click enter key in keyboard will help you. Link: EventListener Enter Key
Also addEventListener "change" will help you.
edit
If you want your data to load when page is loaded use one of those ways:
window.onload = function() {
Search();
} // way one
window.onload = Search(); //way two
<body onclick="Search()"> // way three

JavaScript not working for all HTML pages

I am working on the tablet's display of a Pepper robot; I have a functional HTML index page comprising a list of questions—each question redirects to its respective HTML when clicked on—, 2 volume buttons and 2 other buttons—one that pops up an instruction image and the other one that closes the index page and gets back to the splash screen, which when clicked upon, reveals the index page. So far everything is working. The issue is that when I click a question—I get redirected to its HTML page, but then I get stuck there, as neither the 2 volume buttons nor the 2 other buttons work;
I made sure to include the following in each HTML page:
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
I also reused the same JavaScript functions that worked for the index page.
I commented out some line:
btnPrevious.addEventListener('click', goToPreviousPage);
because I noticed it prevented the splash screen from disappearing when clicked on—i.e., the visibility attribute stays on visible instead of switching to hidden thus revealing the index page, but still, the 3 remaining buttons don't work anyway.
Here is my faq.js code:
/* global QiSession */
var serviceName = 'ADFAQ';
var volumeUpEvent = serviceName + '/VolumeUp';
var volumeDownEvent = serviceName + '/VolumeDown';
var volumeData = serviceName + '/Volume';
/* Clickable buttons */
var btnReturn = document.getElementById('return');
var btnHelp = document.getElementById('call_help');
var btnPrevious = document.getElementById('previous_page');
var btnVolUp = document.getElementById('volume-up');
var btnVolDown = document.getElementById('volume-down');
/* Help image and splash screen */
var helper = document.getElementById('helper');
var img = document.getElementById('click_on_me');
var memory;
var volume;
var audioDevice;
QiSession(connected, disconnected);
function connected (s) {
console.log('QiSession connected');
var questions = document.getElementById('questions');
/* Associating buttons to their respective functions */
btnHelp.addEventListener('click', showHelper);
btnReturn.addEventListener('click', closeQuestions);
//btnPrevious.addEventListener('click', goToPreviousPage);
btnVolUp.addEventListener('click', raiseVolume);
btnVolDown.addEventListener('click', lowerVolume);
img.addEventListener('click', loadQuestions);
questions.addEventListener('click', clickOnQuestion);
s.service('ALMemory').then(function (m) {
m.subscriber(serviceName + '/DialogEnded').then(function (subscriber) {
subscriber.signal.connect(hideQuestions);
});
m.subscriber(serviceName + '/Pepper').then(function (subscriber) {
subscriber.signal.connect(displayPepperHTML)
});
m.subscriber(serviceName + '/RaiseVolume').then(function (subscriber) {
subscriber.signal.connect(raiseVolume);
});
m.subscriber(serviceName + '/LowerVolume').then(function (subscriber) {
subscriber.signal.connect(lowerVolume);
});
memory = m;
});
s.service('ALAudioDevice').then(function (a) {
a.getOutputVolume().then(assignVolume);
audioDevice = a
});
}
function disconnected () {
console.log('QiSession disconnected');
}
function assignVolume(value){
volume = value;
}
function raiseVolume (event) {
var changed = 0;
if(volume < 100) {
volume = Math.min(volume + 5, 100);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeUpEvent, changed);
}
function lowerVolume (event) {
var changed = 0;
if(volume > 30) {
volume = Math.max(volume - 5, 0);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeDownEvent, changed);
}
function showHelper (event) {
if (btnHelp.innerHTML === '?') {
helper.style.opacity = '1';
helper.style.zIndex = '1';
btnHelp.innerHTML = '←';
} else {
helper.style.opacity = '0';
helper.style.zIndex = '-1';
btnHelp.innerHTML = '?';
}
btnHelp.blur();
}
function loadQuestions (event) {
memory.raiseEvent(serviceName + '/LoadQuestions', 1);
img.style.visibility = 'hidden';
}
function goToPreviousPage () {
window.location.href = "index.html";
}
function displayPepperHTML() {
window.location.href = "pepper.html";
}
function closeQuestions (event) {
if(location.href != "index.html")
{window.location.href = "index.html";}
memory.raiseEvent(serviceName + '/CloseQuestions', 1);
btnReturn.blur();
}
function hideQuestions (data) {
if (data !== 0) {
img.style.visibility = 'visible';
helper.style.opacity = '0';
btnHelp.innerHTML = '?';
}
}
function clickOnQuestion (event) {
memory.raiseEvent(serviceName + '/' + event.target.id, 1);
}
Here is my non-functioning pepper.html code:
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Pepper</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=1280, user-scalable=no" />
<link type="text/css" rel="stylesheet" href="css/style.css" />
<link type="text/css" rel="stylesheet" href="css/faq.css" />
</head>
<body>
<header>
<h1>Bla bla bla</h1>
<span class="buttons">
<button id="previous_page" class="button-help"> ← </button>
<button id="return" class="button-return">X</button>
</span>
<div id="helper" class="pop-up">
<img src="img/interactionscreen_frf.png" alt="Bla bla bla">
</div>
</header>
<ul id="questions">
<p>
Bla bla bla
</p>
<div class="volume-part">
<div id="volume-up" class="Click-me">+</div>
<img src="img/speaker.png" alt="Bla bla bla" style="vertical-align: middle;">
<div id="volume-down" class="Click-me">-</div>
</div>
</ul>
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
</body>
</html>
Thank you for your help.
I am expecting the pepper.html page to respond to both the volume and ← and X buttons, as the index.html should, since they use the exact same Javascript.
I was able to find some workaround: creating one JavaScript file for each HTML page, this is redundant and non-optimal I know, but at least it works.
This also made me realize that the commented-out line was blocking the program because the index.html page doesn't use the previous_page button, that's what led me to make a JS file for each HTML page.
If anybody has any other suggestions I am all ears.
Edit: I reduced the number of JS scripts to only 2. One for the index.html and the other for the identically-structured html pages of the other questions.

both jQuery and $ is not a function

I already imported
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
under the head section. But still I got,
RelatedObjectLookups.js:142 Uncaught TypeError: $ is not a function
at RelatedObjectLookups.js:142
at RelatedObjectLookups.js:175
(anonymous) # RelatedObjectLookups.js:142
(anonymous) # RelatedObjectLookups.js:175
(index):177 Uncaught TypeError: $ is not a function
at (index):177
Relavant html looks like,
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script crossorigin="anonymous" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script crossorigin="anonymous" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link crossorigin="anonymous" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" rel="stylesheet">
</head>
<body>
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="/static/admin/js/core.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"> </script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/static/admin/js/actions.min.js"></script>
<script type="text/javascript" src="/static/admin/js/calendar.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/DateTimeShortcuts.js"></script>
{{form.media}}
<div class="row">
<div class="col-6">
<form method="post" id="extendTrialForm" class="form">
{% csrf_token %}
{% bootstrap_field form.user %}
{% bootstrap_field form.core_instance %}
{% bootstrap_field form.expiry_datetime %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
</div>
</div>
<script>
$( document ).ready(function() { // line no 177
Removing the script tags above {{form.media}} won't throw any error related to jquery but it misses the widget functionality. I need that script tags but I don't want Jquery to return $ is not a function. I have tried adding $.noconflict, jQuery(document).ready but nothing works.
RelatedObjectsLookups.js
/*global SelectBox, interpolate*/
// Handles related-objects functionality: lookup link for raw_id_fields
// and Add Another links.
(function($) {
'use strict';
// IE doesn't accept periods or dashes in the window name, but the element IDs
// we use to generate popup window names may contain them, therefore we map them
// to allowed characters in a reversible way so that we can locate the correct
// element when the popup window is dismissed.
function id_to_windowname(text) {
text = text.replace(/\./g, '__dot__');
text = text.replace(/\-/g, '__dash__');
return text;
}
function windowname_to_id(text) {
text = text.replace(/__dot__/g, '.');
text = text.replace(/__dash__/g, '-');
return text;
}
function showAdminPopup(triggeringLink, name_regexp, add_popup) {
var name = triggeringLink.id.replace(name_regexp, '');
name = id_to_windowname(name);
var href = triggeringLink.href;
if (add_popup) {
if (href.indexOf('?') === -1) {
href += '?_popup=1';
} else {
href += '&_popup=1';
}
}
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
function showRelatedObjectLookupPopup(triggeringLink) {
return showAdminPopup(triggeringLink, /^lookup_/, true);
}
function dismissRelatedLookupPopup(win, chosenId) {
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem.className.indexOf('vManyToManyRawIdAdminField') !== -1 && elem.value) {
elem.value += ',' + chosenId;
} else {
document.getElementById(name).value = chosenId;
}
win.close();
}
function showRelatedObjectPopup(triggeringLink) {
return showAdminPopup(triggeringLink, /^(change|add|delete)_/, false);
}
function updateRelatedObjectLinks(triggeringLink) {
var $this = $(triggeringLink);
var siblings = $this.nextAll('.change-related, .delete-related');
if (!siblings.length) {
return;
}
var value = $this.val();
if (value) {
siblings.each(function() {
var elm = $(this);
elm.attr('href', elm.attr('data-href-template').replace('__fk__', value));
});
} else {
siblings.removeAttr('href');
}
}
function dismissAddRelatedObjectPopup(win, newId, newRepr) {
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
var elemName = elem.nodeName.toUpperCase();
if (elemName === 'SELECT') {
elem.options[elem.options.length] = new Option(newRepr, newId, true, true);
} else if (elemName === 'INPUT') {
if (elem.className.indexOf('vManyToManyRawIdAdminField') !== -1 && elem.value) {
elem.value += ',' + newId;
} else {
elem.value = newId;
}
}
// Trigger a change event to update related links if required.
$(elem).trigger('change');
} else {
var toId = name + "_to";
var o = new Option(newRepr, newId);
SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId);
}
win.close();
}
function dismissChangeRelatedObjectPopup(win, objId, newRepr, newId) {
var id = windowname_to_id(win.name).replace(/^edit_/, '');
var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]);
var selects = $(selectsSelector);
selects.find('option').each(function() {
if (this.value === objId) {
this.textContent = newRepr;
this.value = newId;
}
});
win.close();
}
function dismissDeleteRelatedObjectPopup(win, objId) {
var id = windowname_to_id(win.name).replace(/^delete_/, '');
var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]);
var selects = $(selectsSelector);
selects.find('option').each(function() {
if (this.value === objId) {
$(this).remove();
}
}).trigger('change');
win.close();
}
// Global for testing purposes
window.id_to_windowname = id_to_windowname;
window.windowname_to_id = windowname_to_id;
window.showRelatedObjectLookupPopup = showRelatedObjectLookupPopup;
window.dismissRelatedLookupPopup = dismissRelatedLookupPopup;
window.showRelatedObjectPopup = showRelatedObjectPopup;
window.updateRelatedObjectLinks = updateRelatedObjectLinks;
window.dismissAddRelatedObjectPopup = dismissAddRelatedObjectPopup;
window.dismissChangeRelatedObjectPopup = dismissChangeRelatedObjectPopup;
window.dismissDeleteRelatedObjectPopup = dismissDeleteRelatedObjectPopup;
// Kept for backward compatibility
window.showAddAnotherPopup = showRelatedObjectPopup;
window.dismissAddAnotherPopup = dismissAddRelatedObjectPopup;
$(document).ready(function() {
$("a[data-popup-opener]").click(function(event) {
event.preventDefault();
opener.dismissRelatedLookupPopup(window, $(this).data("popup-opener"));
});
$('body').on('click', '.related-widget-wrapper-link', function(e) {
e.preventDefault();
if (this.href) {
var event = $.Event('django:show-related', {href: this.href});
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
showRelatedObjectPopup(this);
}
}
});
$('body').on('change', '.related-widget-wrapper select', function(e) {
var event = $.Event('django:update-related');
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
updateRelatedObjectLinks(this);
}
});
$('.related-widget-wrapper select').trigger('change');
$('body').on('click', '.related-lookup', function(e) {
e.preventDefault();
var event = $.Event('django:lookup-related');
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
showRelatedObjectLookupPopup(this);
}
});
});
})(django.jQuery);
I’m pretty sure your whole problem is that the very end of your RelatedObjectsLookups.js JS file says django.jQuery, which doesn’t exist (or at least, the googleapis jQuery file you’re loading in isn’t going to define that). Change it to window.jQuery and things should work for you.
EDIT based on your reply
Since you can’t change the line that says django.jQuery, then let’s define that.
Right after you include your jQuery file, add the following tag.
<script>
django = django || {};
django.jQuery = django.jQuery || jQuery;
</script>
This will set django.jQuery to jQuery (which is included by your googleapis file), if it’s not been set yet. Now it will exist for your later scripts to use.

Trouble adding search widget to ArcGIS Shortlist Story App

I 'm having issues adding in a search widget to a shortlist application. I have included the code below. The search bar shows up, but is not functional.
I am needing to have this to where it can search business names that are included within the application.
<html>
<head>
<title>ChahtaPreneur</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link type="image/ico" rel="shortcut icon" href="//resources.esri.com/favicon.ico">
<link type="image/ico" rel="icon" href="//resources.esri.com/favicon.ico">
<link rel="stylesheet" href="https://js.arcgis.com/3.18/esri/css/esri.css">
<script src="https://js.arcgis.com/3.18/"></script>
<link rel="stylesheet" href="https://js.arcgis.com/3.18/esri/css/esri.css">
<link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.2/js/dojo/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.5/js/esri/css/esri.css">
<link rel="stylesheet" type="text/css" href="colorbox/colorbox.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="lib/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="lib/common/helper_functions.js"></script>
<script type="text/javascript">var djConfig = {parseOnLoad: true};</script>
<script type="text/javascript" src="colorbox/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="lib/jquery.animate-colors-min.js"></script>
<script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/3.5/"></script>
<style>
html,body,
#mapDiv,.map.container{
padding:0;
margin:0;
height:100%;
}
#search {
display: block;
position: absolute;
z-index: 2;
top: 20px;
left: 720px;
}
</style>
<script src="https://js.arcgis.com/3.18/"></script>
<!--
To correctly reference your Shortlist in search engine:
- create and fill out extensively an ArcGIS Online item that link to your final application
- edit the following four tags as well as the title tag above on line 4
-->
<meta name="description" content="This story map was created with the Story Map Shortlist application in ArcGIS Online.">
<!-- Facebook sharing -->
<meta property="og:type" content="article"/>
<meta property="og:title" content="Story Map Shortlist"/>
<meta property="og:description" content="This story map was created with the Story Map Shortlist application in ArcGIS Online."/>
<meta property="og:image" content="resources/common/icons/esri-globe.png"/>
<!--
This application is released under the Apache License V2.0 by Esri http://www.esri.com/
Checkout the project repository on GitHub to access source code, latest revision, developer documentation, FAQ and tips
https://github.com/Esri/shortlist-storytelling-template-js
-->
<script type="text/javascript">
//-------------------------------------------------------------------------------------------
// Application configuration (ignored on ArcGIS Online, Portal and during development)
//-------------------------------------------------------------------------------------------
var configOptions = {
// Enter an application ID created through the Shortlist builder
appid: "f8c9b5d9a2c64703bb72910f46f59d7c",
// Optionally to secure Shortlist's access, use an OAuth application ID (example: 6gyOg377fLUhUk6f)
// User will need to sign-in to access the viewer even if your application is public
oAuthAppId: "",
// Optionally to be able to use the appid URL parameter, configure here the list of application author
// whose application are allowed to be viewed by this Shortlist deployment
// This is the Portal username of the Shortlist owner (e.g. ["user1"], ["user1", "user2"])
authorizedOwners: ["*"]
};
// Optionally sharing and proxy URLs can be configured in app/config.js. This is only required
// when the webmap is not hosted on ArcGIS Online or a Portal for ArcGIS instance and the application isn't deployed as /home/Shortlist/ or /apps/Shortlist/.
// Optionally Bing Maps key, Geometry and Geocode service's URLs can be configured in app/config.js. This is only required
// if the Organization or Portal for ArcGIS instance default configuration has to be overwritten.
</script>
<script type="text/javascript">
dojo.require("dijit.dijit");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("esri.map");
dojo.require("esri.arcgis.utils");
dojo.require("esri.dijit.Geocoder");
/******************************************************
******************** config section ******************
*******************************************************/
var WEBMAP_ID = "6b3d1da24e5841f1b8d47de63b7be7a4";
var BOOKMARKS_ALIAS = "Zoom";
var COLOR_ORDER = "green,red,blue,purple"; // will only use as many colors as you have content (point) layers
var BINGMAPS_KEY = "";
/******************************************************
******************** app variables ********************
*******************************************************/
var _contentLayers = [];
var _isMobile = isMobile();
var _map;
var _bookmarks;
var _layerCurrent;
var _selected;
var _initExtent;
var _dojoReady = false;
var _jqueryReady = false;
var geocoder;
var locatorUrl = "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/";
/******************************************************
************************* init ************************
*******************************************************/
dojo.addOnLoad(function() {_dojoReady = true;init()});
jQuery(document).ready(function() {_jqueryReady = true;init()});
/* init comes in two parts because of async call to
createMap. */
function init() {
if (!_jqueryReady) return;
if (!_dojoReady) return;
if (getParameterByName("webmap") != "") {
WEBMAP_ID = getParameterByName("webmap");
}
if (getParameterByName("bookmarks_alias") != "") {
BOOKMARKS_ALIAS = getParameterByName("bookmarks_alias");
}
if (getParameterByName("color_order") != "") {
COLOR_ORDER = getParameterByName("color_order")
}
$("#bookmarksTogText").html(BOOKMARKS_ALIAS+' ▼');
$(this).resize(handleWindowResize);
$("#zoomIn").click(function(e) {
_map.setLevel(_map.getLevel()+1);
});
$("#zoomOut").click(function(e) {
_map.setLevel(_map.getLevel()-1);
});
$("#zoomExtent").click(function(e) {
_map.setExtent(_initExtent);
});
$(document).bind('cbox_complete', function(){
$(".details .rightDiv").height($(".details").height() - 65);
});
$("#bookmarksToggle").click(function(){
if ($("#bookmarksDiv").css('display')=='none'){
$("#bookmarksTogText").html(BOOKMARKS_ALIAS+' ▲');
}
else{
$("#bookmarksTogText").html(BOOKMARKS_ALIAS+' ▼');
}
$("#bookmarksDiv").slideToggle();
});
var mapDeferred = esri.arcgis.utils.createMap(WEBMAP_ID, "map", {
mapOptions: {
slider: false,
wrapAround180:false
},
ignorePopups: true,
bingMapsKey: BINGMAPS_KEY
});
mapDeferred.addCallback(function(response) {
document.title = response.itemInfo.item.title;
$("#title").html(response.itemInfo.item.title);
$("#subtitle").html(response.itemInfo.item.snippet);
_map = response.map;
//resize the map when the browser resizes
dojo.connect(dijit.byId('map'), 'resize', _map,_map.resize);
dojo.connect(_map, 'onExtentChange', refreshList);
// click action on the map where there's no graphic
// causes a deselect.
dojo.connect(_map, 'onClick', function(event){
if (event.graphic == null) {
unselect();
}
});
_bookmarks = response.itemInfo.itemData.bookmarks;
if (_bookmarks) {
loadBookmarks();
$("#bookmarksCon").show();
}
var layers = response.itemInfo.itemData.operationalLayers;
if(_map.loaded){
initMap(layers);
} else {
dojo.connect(_map,"onLoad",function(){
initMap(layers);
});
}
});
mapDeferred.addErrback(function(error) {
console.log("Map creation failed: ", dojo.toJson(error));
});
}
function initMap(layers) {
var supportLayers = [];
var pointLayers = [""];
$.each(layers,function(index,value){
if (value.url == null) {
if (value.featureCollection.layers[0].featureSet.geometryType == "esriGeometryPoint") {
pointLayers.push(value);
} else {
supportLayers.push(value);
}
} else {
// if the layer has an url property (meaning that it comes from a service), just
// keep going...it will remain in the map, but won't be query-able.
}
});
_initExtent = _map.extent;
var supportLayer;
$.each(supportLayers,function(index,value) {
supportLayer = findLayer(_map,value.title);
if (supportLayer == null) return;
$.each(supportLayer.graphics,function(index,value) {
value.attributes.getValueCI = getValueCI; // assign extra method to handle case sensitivity
});
dojo.connect(supportLayer, "onMouseOver", baselayer_onMouseOver);
dojo.connect(supportLayer, "onMouseOut", baselayer_onMouseOut);
dojo.connect(supportLayer, "onClick", baselayer_onClick);
});
if (COLOR_ORDER.split(",").length < pointLayers.length) {
// you have supplied fewer colors than point layers and
// therefore have lost your sorting privileges...
colorschemes = COLOR_SCHEMES;
} else {
// sort the colors
var colorschemes = getSortedColorSchemes();
// burn off any extra colors, if you have more colors
// than points.
while (pointLayers.length < colorschemes.length) {
colorschemes.shift()
};
}
var contentLayer;
$.each(pointLayers,function(index,value) {
_map.removeLayer(findLayer(_map,value.title));
if (index <= 4) { // maximum of 4 point layers.
$.each(value.featureCollection.layers[0].featureSet.features,function(index,value) {
value.attributes.getValueCI = getValueCI; // assign extra method to handle case sensitivity
});
contentLayer = buildLayer(
value.featureCollection.layers[0].featureSet.features.sort(SortByID),
colorschemes[index].iconDir,
colorschemes[index].iconPrefix
);
contentLayer.color = colorschemes[index].color;
contentLayer.title = value.title;
dojo.connect(contentLayer, "onMouseOver", layer_onMouseOver);
dojo.connect(contentLayer, "onMouseOut", layer_onMouseOut);
dojo.connect(contentLayer, "onClick", layer_onClick);
_map.addLayer(contentLayer);
_contentLayers.push(contentLayer);
}
});
_contentLayers.reverse();
$.each(_contentLayers,function(index,value){
$("#tabs").append('<div class="tab" onclick="activateLayer(_contentLayers['+index+'])">'+value.title+'</div>');
});
activateLayer(_contentLayers[0]);
dojo.connect(_map.infoWindow,"onHide",infoWindow_onHide);
handleWindowResize();
$("#zoomToggle").css("visibility","visible");
// Solomon Additions
// add a graphics layer for geocoding results
_map.addLayer(new esri.layers.GraphicsLayer({
id: "results"
}));
var myGeocoders = [{
url: locatorUrl,
name: "Single_Line"
}];
// create the geocoder
geocoder = new esri.dijit.Geocoder({
autoComplete : true,
autoNavigate: true,
localSearchOptions : {
minScale : 3,
distance : 4000},
maxLocations : 20,
arcgisGeocoder: false,
geocoders:myGeocoders,
value:'Search by Name',
map : _map
}, "search");
geocoder.startup();
geocoder.focus();
var symbol = new esri.symbol.PictureMarkerSymbol({
"angle":0,
"xoffset":0,
"yoffset":10,
"type":"esriPMS",
"url":"http://static.arcgis.com/images/Symbols/Shapes/BluePin1LargeB.png",
"contentType":"image/png",
"width":24,
"height":24
});
var template = new esri.InfoTemplate("${NAME}", "${*}");
dojo.connect(geocoder, "onFindResults", function(response) {
//STEVE CHANGES
//Use first match
//var name = response.results[0].name;
//Match name with locations layer and selected that index
//for(i in _locations){
//if(name === _locations[i].attributes.getName()){
//preSelection()
//_selected = _locations[i];
//postSelection();
//}
//}
//STEVE CHANGES END
console.log("find results: ", response);
var l = _map.getLayer("shortlistlayer");
l.clear();
_map.infoWindow.hide();
dojo.forEach(response.results, function(r) {
r.feature.attributes.NAME = r.NAME;
r.feature.setSymbol(symbol);
r.feature.setInfoTemplate(template);
l.add(r.feature);
});
});
// solomon Addition Ends
}
/******************************************************
******************** event handlers *******************
*******************************************************/
function tile_onMouseOver(e) {
$(this).stop().animate({'background-color' : COLOR_FULL});
}
function tile_onMouseOut(e) {
if (_selected != null) {
// does this tile represent the selected graphic?
var id = parseInt($(this).attr("id").substring(4));
if (_selected.attributes.getValueCI("Number") == id) {
return;
}
}
$(this).stop().animate({'background-color' : COLOR_DIM});
}
function tile_onClick(e) {
// turn off the last selected tile...
if (_selected != null) {
var tile = $.grep($("ul.tilelist li"),function(n,i){return n.id == "item"+_selected.attributes.getValueCI("Number")})[0];
if ($(tile).attr("id") != $(this).attr("id")) $(tile).stop().animate({'background-color' : COLOR_DIM});
}
$(this).stop().animate({'background-color' : COLOR_FULL});
var id= $(this).attr("id").substring(4);
_selected = $.grep(_layerCurrent.graphics,function(n,i){return n.attributes.getValueCI("Number") == id})[0];
postSelection();
}
function infoWindow_onHide(event) {
unselect();
}
function baselayer_onMouseOver(event)
{
if (_isMobile) return;
_map.setMapCursor("pointer");
var graphic = event.graphic;
$("#hoverInfo").html(graphic.attributes.getValueCI("Title"));
var pt = event.screenPoint;
hoverInfoPos(pt.x,pt.y);
}
function baselayer_onMouseOut(event)
{
if (_isMobile) return;
_map.setMapCursor("default");
$("#hoverInfo").hide();
}
function baselayer_onClick(event) {
var feature = event.graphic;
_map.infoWindow.setTitle(event.graphic.attributes.getValueCI("NAME"));
_map.infoWindow.setContent(event.graphic.attributes.getValueCI("CAPTION")+"<p><span class='infoWindowLink'>Details >></span></p>");
_map.infoWindow.show(event.mapPoint);
$(".infoWindowLink").click(function(e) {
showDetails(feature);
});
$("#hoverInfo").hide();
}
function layer_onClick(event)
{
var tile;
if (_selected != null) {
tile = $.grep($("ul.tilelist li"),function(n,i){return n.id == "item"+_selected.attributes.getValueCI("Number")})[0]
$(tile).stop().animate({'background-color' : COLOR_DIM});
}
_selected = event.graphic;
tile = $.grep($("ul.tilelist li"),function(n,i){return n.id == "item"+_selected.attributes.getValueCI("Number")})[0]
$(tile).stop().animate({'background-color' : COLOR_FULL});
postSelection();
}
function layer_onMouseOver(event)
{
if (_isMobile) return;
_map.setMapCursor("pointer");
var graphic = event.graphic;
if (graphic == _selected) return;
graphic.setSymbol(graphic.symbol.setHeight(30).setWidth(24));
$("#hoverInfo").html(graphic.attributes.getValueCI("NAME"));
var pt = _map.toScreen(graphic.geometry);
hoverInfoPos(pt.x,pt.y);
}
function layer_onMouseOut(event)
{
if (_isMobile) return;
_map.setMapCursor("default");
var graphic = event.graphic;
graphic.setSymbol(graphic.symbol.setHeight(28).setWidth(22));
$("#hoverInfo").hide();
}
/******************************************************
****************** other functions ********************
*******************************************************/
function unselect() {
if (_selected != null) {
tile = $.grep($("ul.tilelist li"),function(n,i){return n.id == "item"+_selected.attributes.getValueCI("Number")})[0]
$(tile).stop().animate({'background-color' : COLOR_DIM});
}
_selected = null;
postSelection();
}
// sort items by numeric ID
function SortByID(a, b){
var aID = a.attributes.getValueCI("Number");
var bID = b.attributes.getValueCI("Number");
return ((aID < bID) ? -1 : ((aID > bID) ? 1 : 0));
}
function loadBookmarks() {
$.each(_bookmarks,function(index,value){$("#bookmarksDiv").append("<p><a>"+value.name+"</a></p>")});
$("#bookmarksDiv a").click(function(e) {
var name = $(this).html();
var extent = new esri.geometry.Extent($.grep(_bookmarks,function(n,i){return n.name == name})[0].extent);
_map.setExtent(extent);
$("#bookmarksTogText").html(BOOKMARKS_ALIAS+' ▼');
$("#bookmarksDiv").slideToggle();
});
}
function activateLayer(layer) {
_selected = null;
postSelection();
_layerCurrent = layer;
var tab = $.grep($(".tab"),function(n,i){return $(n).html() == _layerCurrent.title})[0];
$(".tab").removeClass("tab-selected");
$(tab).addClass("tab-selected");
$.each(_contentLayers,function(index,value){
value.setVisibility(value == _layerCurrent);
});
$("#myList").empty();
var display;
var tile;
var img;
var footer;
var num;
var title;
$.each(_layerCurrent.graphics,function(index,value){
if (_map.extent.contains(value.geometry)) {
display = "visible"
} else {
display = "none";
}
tile = $('<li id="item'+value.attributes.getValueCI("Number")+'" style="display:'+display+'">');
img = $('<img src="'+value.attributes.getValueCI("THUMB_URL")+'">');
footer = $('<div class="footer"></div>');
num = $('<div class="num" style="background-color:'+_layerCurrent.color+'">'+value.attributes.getValueCI("Number")+'</div>');
title = $('<div class="blurb">'+value.attributes.getValueCI("Name")+'</div>');
$(footer).append(num);
$(footer).append(title);
$(tile).append(img);
$(tile).append(footer);
$("#myList").append(tile);
});
// event handlers have to be re-assigned every time you load the list...
$("ul.tilelist li").mouseover(tile_onMouseOver);
$("ul.tilelist li").mouseout(tile_onMouseOut);
$("ul.tilelist li").click(tile_onClick);
$("ul.tilelist").animate({ scrollTop: 0 }, { duration: 200 } );
}
function refreshList() {
var tile;
$.each(_layerCurrent.graphics,function(index,value){
//find the corresponding tile
tile = $.grep($("ul.tilelist li"),function(n,i){return n.id == "item"+value.attributes.getValueCI("Number")})[0];
if (_map.extent.contains(value.geometry)) {
if ($(tile).css("display") == "none") $(tile).stop().fadeIn();
} else {
if ($(tile).css("display") != "none") $(tile).stop().fadeOut(1000);
}
});
}
function buildLayer(arr,iconDir,root) {
var layer = new esri.layers.GraphicsLayer();
var pt;
var sym;
$.each(arr,function(index,value){
pt = new esri.geometry.Point(value.geometry.x,value.geometry.y,value.geometry.spatialReference);
sym = new esri.symbol.PictureMarkerSymbol("images/icons/"+iconDir+"/"+root+value.attributes.getValueCI("Number")+".png",22,28);
layer.add(new esri.Graphic(pt,sym,value.attributes));
});
return layer;
}
function getValueCI(field) {
var found;
$.each(this,function(index,value){
if (index.toUpperCase() == field.toUpperCase()) {
found = index;
return false;
}
});
return this[found];
}
function handleWindowResize() {
var heightDoc = getViewportDimensions()[1];
$("#mainWindow").height(heightDoc - ($("#header").height()));
dijit.byId("mainWindow").layout();
$("#paneLeft").height($("#mainWindow").height() - 35);
$(".tilelist").height($("#paneLeft").height() - 20);
$("#map").height($("#mainWindow").height() - 35);
Well, I went though your code the major error i can see is that multiple define error.
Root Cause:
The main reason for it you are loading those libraries more than once who expose define.
Solution:
In your case i noticed you have loaded ArcGIS JS Api more than once.
Just load only one source of ArcGIS it should work.
One more thinh in attached code you are using multiple versions of CSS.
you are suppose to use same version of ESRI CSS which you are using for JS.
As per your code you are using legacy model of coding style so go for arcgis js api's that version only.
Code without multiple define error: https://jsfiddle.net/vikash2402/362ft9g7/
Hoping this will help you :)
Well, Here is the working code for esri search widget.
Just require the needed libraries and plugin the code.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />
<title>Search with Suggestion Template</title>
<link rel="stylesheet" href="https://js.arcgis.com/3.18/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="https://js.arcgis.com/3.18/esri/css/esri.css">
<style>
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#search {
display: block;
position: absolute;
z-index: 2;
top: 20px;
left: 74px;
}
</style>
<script src="https://js.arcgis.com/3.18/"></script>
<script>
require([
"esri/map", "esri/dijit/Search", "esri/layers/FeatureLayer", "esri/InfoTemplate", "dojo/domReady!"
], function (Map, Search, FeatureLayer,InfoTemplate) {
var map = new Map("map", {
basemap: "gray",
center: [-82.93, 42.5], // lon, lat
zoom: 10
});
var search = new Search({
sources: [{
featureLayer: new FeatureLayer("https://services.arcgis.com/b6gLrKHqgkQb393u/arcgis/rest/services/TaxParcelQuery/FeatureServer/0", {
outFields: ["*"],
infoTemplate: new InfoTemplate("Parcels", "Owner name: ${OWNERNME1}</br>Parcel ID: ${PARCELID}</br>Site address: ${SITEADDRESS}")
}),
outFields: ["OWNERNME1","PARCELID","SITEADDRESS"],
displayField: "OWNERNME1",
suggestionTemplate: "${PARCELID}: ${SITEADDRESS}",
name: "Parcels",
placeholder: "example: Shawn Smith",
enableSuggestions: true
}],
map: map
}, "search");
search.startup();
});
</script>
</head>
<body>
<div id="search"></div>
<div id="map"></div>
</body>
</html>
Hoping this will help you :)

Data source query callback problems (call order, ability to change global variables)

I've reduced my code to the following short example. In it, I want to query for a set of iterations, and then in the callback, loop over the iterations and sum the resources. There is a global variable in which I'd like to store the sum... but I can't get this to work.
The specific problem is that the query (and associated callback) are run after the other processing.
<html><!-- COMMENT -->
<meta name="Name" content="YOUR APP NAME HERE" />
<meta name="Version" content="0.1" />
<meta name="Vendor" content="YOUR COMPANY NAME HERE" />
<!-- Rally SDK --> <script type="text/javascript" src="/apps/1.25/sdk.js"></script>
<!-- App script --> <script>
var rallyDataSource; var resourceSum = -1;
function ProcessIterations(results) {
alert("In ProcessIterations");
var resourceSum = 0;
for (iIter = 0; iIter < results.iterations.length; iIter++) {
var iteration = results.iterations[iIter] ;
resourceSum += iteration.Resources;
}
alert("In ProcessIterations, resourceSum="+resourceSum); }
function queryError () {
alert("A query error occurred"); }
function runMainQuery() { var today = dojo.date.stamp.toISOString(new Date(), {milliseconds: true, zulu: true});
var queryObject = {
key: "iterations",
type: "Iteration",
fetch: "Name,ObjectID,Resources,Project",
order: "EndDate asc",
query: "(Project.ObjectID != \"__PROJECT_OID__\")"
};
rallyDataSource.findAll(queryObject, ProcessIterations, queryError); }
function Main() { rallyDataSource = new rally.sdk.data.RallyDataSource("__WORKSPACE_OID__", "__PROJECT_OID__",
"__PROJECT_SCOPING_UP__", "__PROJECT_SCOPING_DOWN__");
runMainQuery() ;
var tableConfig = {
'columnKeys' : ['planEst'],
'columnHeaders': ['Plan Estimate'] }; var table = new rally.sdk.ui.Table(tableConfig); table.setCell(0,0,resourceSum) ; table.display("app_div");
}
rally.addOnLoad(Main);
</script> <body>
<div id="app_div"></div>
<div id="error_div"></div> </body> </html>
It can be a little tricky to get the hang of asynchronous callbacks but you're really close.
Basically if you just move the creation of your table from Main to up in your ProcessIterations callback you should be good:
function ProcessIterations(results) {
alert("In ProcessIterations");
var resourceSum = 0;
for (iIter = 0; iIter < results.iterations.length; iIter++) {
var iteration = results.iterations[iIter] ;
resourceSum += iteration.Resources;
}
alert("In ProcessIterations, resourceSum="+resourceSum); }
var tableConfig = {
'columnKeys' : ['planEst'],
'columnHeaders': ['Plan Estimate'] };
var table = new rally.sdk.ui.Table(tableConfig);
table.setCell(0,0,resourceSum) ;
table.display("app_div");
}
function Main() {
rallyDataSource = new rally.sdk.data.RallyDataSource("__WORKSPACE_OID__", "__PROJECT_OID__",
"__PROJECT_SCOPING_UP__", "__PROJECT_SCOPING_DOWN__");
runMainQuery() ;
}
That way you won't display your table until the data is available from your rallyDataSource.findAll call and your resourceSum has been calculated.
As an additional resource checkout some of the examples in our help documentation on using RallyDataSource and async callbacks:
http://developer.rallydev.com/help/rally-data-source

Categories

Resources