Http Adapter Invocation failure? - ibm-mobilefirst

The Control is going to failure function when I'm trying to invoke Http Adapter.Here My adapter is running fine and I'm getting data also.
Here is My html code
<html>
<head>
<meta charset="UTF-8">
<title>IIB_WL_App</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
<link rel="stylesheet" href="css/IIB_WL_App.css">
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body id="content" style="display: none;">
<form name="f1">
Enter Employee ID :<input type="text" id="EmpId">
<br>
<input type="submit" value="GetDetails" onclick="GetDetails()">
</form>
<!--application UI goes here-->
<script src="js/initOptions.js"></script>
<script src="js/IIB_WL_App.js"></script>
<script src="js/messages.js"></script>
</body>
</html>
Here is My .js code For getting details
function GetDetails(){
//alert("Function Called");
var id=f1.EmpId.value;
//var id=document.getElementById("EmpId").value();
alert(id);
var invocationData = {
adapter : 'IIB_WL_Adapter',
procedure : 'getData',
parameters : [id]
};
var options={
onSuccess : getDataSuccess,
onFailure : getDataFailure,
};
WL.Client.invokeProcedure(invocationData,options);
};
function getDataSuccess(result) {
//WL.Logger.debug("Retrieve success" + JSON.stringify(result));
alert("Success");
var httpStatusCode = result.status;
alert(httpStatusCode);
}
function getDataFailure(result) {
//WL.Logger.debug("Retrieve success" + JSON.stringify(result));
alert("Failure");
var httpStatusCode = result.status;
alert(httpStatusCode);
}
And I want to display that data in a list view
Here is MY adapter.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- Licensed Materials - Property of IBM 5725-G92 (C) Copyright IBM Corp.
2011, 2013. All Rights Reserved. US Government Users Restricted Rights -
Use, duplication or disclosure restricted by GSA ADP Schedule Contract with
IBM Corp. -->
<wl:adapter name="IIB_WL_Adapter" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wl="http://www.worklight.com/integration" xmlns:http="http://www.worklight.com/integration/http">
<displayName>IIB_WL_Adapter</displayName>
<description>IIB_WL_Adapter</description>
<connectivity>
<connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
<protocol>http</protocol>
<domain>172.17.14.228</domain>
<port>7080</port>
<!-- Following properties used by adapter's key manager for choosing specific
certificate from key store <sslCertificateAlias> </sslCertificateAlias> <sslCertificatePassword></sslCertificatePassword> -->
</connectionPolicy>
<loadConstraints maxConcurrentConnectionsPerNode="2" />
</connectivity>
<procedure name="getData" />
Here is My adpater-impl.js
function getData(interest) {
//path = getPath(interest);
var input = {
method : 'get',
path : '/DBRetrive',
returnedContentType : 'xml',
parameters : {'id' : interest}
};
return WL.Server.invokeHttp(input);
}

I got the solution for this problem. The problem is in my Html page i.e instead of using this.
<input type="submit" value="GetDetails" onclick="GetDetails()">
use the following tag with button type then its working.
<input type="button" value="GetDetails" onclick="return GetDetails()">
And for displaying the data I added some code in .js file
function GetDetails(){
var id=f1.EmpId.value;
alert(id);
var invocationData = {
adapter : 'IIB_WL_Adapter',
procedure : 'getData',
parameters : [id]
};
var options={
onSuccess : getDataSuccess,
onFailure : getDataFailure,
};
WL.Client.invokeProcedure(invocationData,options);
};
function getDataSuccess(result) {
display(result.invocationResult.Employee.Data);
}
function getDataFailure(result) {
alert(JSON.stringify(result));
alert(result.errorMsg);
var httpStatusCode = result.status;
}
function display(items){
var ul=$("#itemList");
ul=$("#itemList").html("&nbsp");
var li=$('<li/>').html("Id:"+items.ID);
li.append($('<li/>').html("Name:"+items.NAME));
li.append($('<li/>').html("Age:"+items.AGE));
ul.append(li);
}

I've ran your code.
The code itself appears to be sound.
It's failing though, so I don't understand what do you mean by "The Control is going to failure function when I'm trying to invoke Http Adapter.Here My adapter is running fine and I'm getting data also."
You say you tested it in the browser and it is failing with "The Service Currently not available". It is also failing the same for me in the browser, and also the same when invoking the adapter from the Studio - same error message.
So again, where exactly is it working for you?
As I see it, the problem is in your adapter configuration, the location you're pointing to does not exist or is the wrong location to point to: http://172.17.14.228:7080/DBretrieve

Related

custom UI in node-red (node-red-contrib-uibuilder & VueJS & import package)

I use node-red to write data from sensors to the database. I also plan to use it to display data. For display I use node-red-contrib-uibuilder, which, as I understand it, uses VueJS. In the end, everything is fine, everything works. But the problem was revealed. Cannot add package from npm. For example vue-datepicker.
How can I add a package?
Here is the code that is:
HTML:
<!doctype html>
<!-- Note that adding an appcache really speeds things up after the first load
You need to amend the appcache file to meet your needs.
Don't forget to change the appcache file if you update ANY
of the files in it otherwise the old versions will ALWAYS be used.
<html lang="en" manifest="./uibuilder.appcache">
-->
<html lang="en">
<!--
This is the default, template html for uibuilder.
It is meant to demonstrate the use of VueJS & bootstrap-vue to dynamically
update the ui based on incoming/outgoing messages from/to the
Node-RED server.
You will want to alter this to suite your own needs. To do so,
copy this file to <userDir>/uibuilder/<url>/src.
-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<title>Node-RED UI Builder</title>
<meta name="description" content="Node-RED UI Builder - VueJS + bootstrap-vue version">
<link rel="icon" href="./images/node-blue.ico">
<link rel="manifest" href="./manifest.json">
<meta name="theme-color" content="#3f51b5">
<!-- Used if adding to homescreen for Chrome on Android. Fallback for manifest.json -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="application-name" content="Node-RED UI Builder">
<!-- Used if adding to homescreen for Safari on iOS -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="Node-RED UI Builder">
<!-- Homescreen icons for Apple mobile use if required
<link rel="apple-touch-icon" href="./images/manifest/icon-48x48.png">
<link rel="apple-touch-icon" sizes="72x72" href="./images/manifest/icon-72x72.png">
<link rel="apple-touch-icon" sizes="96x96" href="./images/manifest/icon-96x96.png">
<link rel="apple-touch-icon" sizes="144x144" href="./images/manifest/icon-144x144.png">
<link rel="apple-touch-icon" sizes="192x192" href="./images/manifest/icon-192x192.png">
-->
<link type="text/css" rel="stylesheet" href="../uibuilder/vendor/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="../uibuilder/vendor/bootstrap-vue/dist/bootstrap-vue.css" />
<link type="text/css" rel="stylesheet" href="./index.css" media="all">
<!--<script type="tex/javascript" src="https://cdn.jsdelivr.net/npm/vue-datetime#1.0.0-beta.11/dist/vue-datetime.min.js"></script>-->
<!--<script type="tex/javascript" src="https://moment.github.io/luxon/amd/luxon.js"></script>-->
<!--<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vue-datetime#1.0.0-beta.11/dist/vue-datetime.min.css">-->
<!-- <link href="../uibuilder/vendor/air-datetimepicker/dist/css/datepicker.min.css" rel="stylesheet" type="text/css"> -->
</head>
<body class="bg-dark">
<div id="app" v-cloak>
<b-container id="app_container" class="container">
<div class="card shadow mb-4 mt-2">
<div class="card-header">
<span class="h3 text-primary">Данные по датчику</span>
</div>
<div class="card-body">
<div class="row mt-2">
<span class="label my-2 h-4">Название датчика:</span>
<select ref="selectSensor" class="form-control" v-on:input="sensorChange">
<option ref="optionForRemove" value="">Выберите датчик</option>
<option value="1111/Temperature/t1">Температура 1</option>
<option value="1111/Temperature/t2">Температура 2</option>
<option value="1111/Temperature/t3">Температура 3</option>
</select>
</div>
<div class="row mt-2">
<div class="col-6">
<input type='text' class="datepicker-here" data-position="right top" />
</div>
<div class="col-6"></div>
</div>
</div>
<div class="card-footer">
<div class="row mt-2">
<pre v-html="hLastRcvd" class="w-100 syntax-highlight"></pre>
</div>
</div>
</div>
</b-container>
</div>
<!-- These MUST be in the right order. Note no leading / -->
<!-- REQUIRED: Socket.IO is loaded only once for all instances
Without this, you don't get a websocket connection -->
<script src="../uibuilder/vendor/socket.io/socket.io.js"></script>
<!-- --- Vendor Libraries - Load in the right order --- -->
<script src="../uibuilder/vendor/vue/dist/vue.js"></script> <!-- dev version with component compiler -->
<!-- <script src="../uibuilder/vendor/vue/dist/vue.min.js"></script> prod version with component compiler -->
<!-- <script src="../uibuilder/vendor/vue/dist/vue.runtime.min.js"></script> prod version without component compiler -->
<script src="../uibuilder/vendor/bootstrap-vue/dist/bootstrap-vue.js"></script>
<!-- REQUIRED: Sets up Socket listeners and the msg object -->
<!-- <script src="./uibuilderfe.js"></script> //dev version -->
<script src="./uibuilderfe.min.js"></script> <!-- //prod version -->
<!-- OPTIONAL: You probably want this. Put your custom code here -->
<script src="./index.js"></script>
<!-- <script type="text/javascript" src="../../../node_modules/air-datepicker/dist/js/datepicker.min.js"></script> -->
</body>
</html>
JS (esversion: 5):
/* jshint browser: true, esversion: 5, asi: true */
/*globals Vue, uibuilder */
// #ts-nocheck
/*
Copyright (c) 2019 Julian Knight (Totally Information)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
'use strict'
// var datetime = require('vue-datetime');
// import * as name from "vue-datetime";
/** #see https://github.com/TotallyInformation/node-red-contrib-uibuilder/wiki/Front-End-Library---available-properties-and-methods */
// eslint-disable-next-line no-unused-vars
var app1 = new Vue({
el: '#app',
data: {
startMsg : 'Vue has started, waiting for messages',
feVersion : '',
socketConnectedState : false,
serverTimeOffset : '[unknown]',
imgProps : { width: 75, height: 75 },
chartData : null,
msgRecvd : '[Nothing]',
msgsReceived: 0,
msgCtrl : '[Nothing]',
msgsControl : 0,
msgSent : '[Nothing]',
msgsSent : 0,
msgCtrlSent : '[Nothing]',
msgsCtrlSent: 0,
}, // --- End of data --- //
computed: {
hLastRcvd: function() {
this.chartData = this.msgRecvd.chartData;
var msgRecvd = this.msgRecvd
if (typeof msgRecvd === 'string') return 'Last Message Received = ' + msgRecvd
else return 'Last Message Received = ' + this.syntaxHighlight(msgRecvd)
},
hLastSent: function() {
var msgSent = this.msgSent
if (typeof msgSent === 'string') return 'Last Message Sent = ' + msgSent
else return 'Last Message Sent = ' + this.syntaxHighlight(msgSent)
},
hLastCtrlRcvd: function() {
var msgCtrl = this.msgCtrl
if (typeof msgCtrl === 'string') return 'Last Control Message Received = ' + msgCtrl
else return 'Last Control Message Received = ' + this.syntaxHighlight(msgCtrl)
},
hLastCtrlSent: function() {
var msgCtrlSent = this.msgCtrlSent
if (typeof msgCtrlSent === 'string') return 'Last Control Message Sent = ' + msgCtrlSent
//else return 'Last Message Sent = ' + this.callMethod('syntaxHighlight', [msgCtrlSent])
else return 'Last Control Message Sent = ' + this.syntaxHighlight(msgCtrlSent)
},
}, // --- End of computed --- //
methods: {
sensorChange: function(){
this.$refs.optionForRemove.outerHTML = "";
var topic = 'getDataFromSensor';
uibuilder.send( {
'topic': topic,
'payload': {
'sensor':this.$refs.selectSensor.value,
}
} )
},
// --- End of increment --- //
// return formatted HTML version of JSON object
syntaxHighlight: function(json) {
json = JSON.stringify(json, undefined, 4)
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
json = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number'
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key'
} else {
cls = 'string'
}
} else if (/true|false/.test(match)) {
cls = 'boolean'
} else if (/null/.test(match)) {
cls = 'null'
}
return '<span class="' + cls + '">' + match + '</span>'
})
return json
}, // --- End of syntaxHighlight --- //
}, // --- End of methods --- //
// Available hooks: init,mounted,updated,destroyed
mounted: function(){
//console.debug('[indexjs:Vue.mounted] app mounted - setting up uibuilder watchers')
/** **REQUIRED** Start uibuilder comms with Node-RED #since v2.0.0-dev3
* Pass the namespace and ioPath variables if hosting page is not in the instance root folder
* The namespace is the "url" you put in uibuilder's configuration in the Editor.
* e.g. If you get continual `uibuilderfe:ioSetup: SOCKET CONNECT ERROR` error messages.
* e.g. uibuilder.start('uib', '/nr/uibuilder/vendor/socket.io') // change to use your paths/names
*/
uibuilder.start()
var vueApp = this
// Example of retrieving data from uibuilder
vueApp.feVersion = uibuilder.get('version')
/** You can use the following to help trace how messages flow back and forth.
* You can then amend this processing to suite your requirements.
*/
//#region ---- Trace Received Messages ---- //
// If msg changes - msg is updated when a standard msg is received from Node-RED over Socket.IO
// newVal relates to the attribute being listened to.
uibuilder.onChange('msg', function(newVal){
//console.info('[indexjs:uibuilder.onChange] msg received from Node-RED server:', newVal)
vueApp.msgRecvd = newVal
})
// As we receive new messages, we get an updated count as well
uibuilder.onChange('msgsReceived', function(newVal){
//console.info('[indexjs:uibuilder.onChange] Updated count of received msgs:', newVal)
vueApp.msgsReceived = newVal
})
// If we receive a control message from Node-RED, we can get the new data here - we pass it to a Vue variable
uibuilder.onChange('ctrlMsg', function(newVal){
//console.info('[indexjs:uibuilder.onChange:ctrlMsg] CONTROL msg received from Node-RED server:', newVal)
vueApp.msgCtrl = newVal
})
// Updated count of control messages received
uibuilder.onChange('msgsCtrl', function(newVal){
//console.info('[indexjs:uibuilder.onChange:msgsCtrl] Updated count of received CONTROL msgs:', newVal)
vueApp.msgsControl = newVal
})
//#endregion ---- End of Trace Received Messages ---- //
//#region ---- Trace Sent Messages ---- //
// You probably only need these to help you understand the order of processing //
// If a message is sent back to Node-RED, we can grab a copy here if we want to
uibuilder.onChange('sentMsg', function(newVal){
//console.info('[indexjs:uibuilder.onChange:sentMsg] msg sent to Node-RED server:', newVal)
vueApp.msgSent = newVal
})
// Updated count of sent messages
uibuilder.onChange('msgsSent', function(newVal){
//console.info('[indexjs:uibuilder.onChange:msgsSent] Updated count of msgs sent:', newVal)
vueApp.msgsSent = newVal
})
// If we send a control message to Node-RED, we can get a copy of it here
uibuilder.onChange('sentCtrlMsg', function(newVal){
//console.info('[indexjs:uibuilder.onChange:sentCtrlMsg] Control message sent to Node-RED server:', newVal)
vueApp.msgCtrlSent = newVal
})
// And we can get an updated count
uibuilder.onChange('msgsSentCtrl', function(newVal){
//console.info('[indexjs:uibuilder.onChange:msgsSentCtrl] Updated count of CONTROL msgs sent:', newVal)
vueApp.msgsCtrlSent = newVal
})
//#endregion ---- End of Trace Sent Messages ---- //
// If Socket.IO connects/disconnects, we get true/false here
uibuilder.onChange('ioConnected', function(newVal){
//console.info('[indexjs:uibuilder.onChange:ioConnected] Socket.IO Connection Status Changed to:', newVal)
vueApp.socketConnectedState = newVal
})
// If Server Time Offset changes
uibuilder.onChange('serverTimeOffset', function(newVal){
//console.info('[indexjs:uibuilder.onChange:serverTimeOffset] Offset of time between the browser and the server has changed to:', newVal)
vueApp.serverTimeOffset = newVal
})
} // --- End of mounted hook --- //
}) // --- End of app1 --- //
// EOF
Whenever a package is available on npm, you can also get it via the jsdelivr CDN: https://www.jsdelivr.com/.
For example for vue-datepicker, use : https://cdn.jsdelivr.net/npm/vue-datepicker/ -> This will give you a listing of available files.
Use https://cdn.jsdelivr.net/npm/vue-datepicker/filename and add it as a script tag to the bottom of your uibuilder's index.html like this: <script src="https://cdn.jsdelivr.net/npm/vue-datepicker"></script>
After that, you can use it in index.js.
You can add modules from NPM in the uibuilder node.
Click "manage front end libraries" from the uibuilder node options and it brings up a graphical interface for NPM.
They will go in your node-red node_modules folder (by default, ~/.node-red/node_modules)

Data insertion in already created table in sql using mobile first studio

kindly need ur help.i have copy pasted and modified the below project from idan adar post about inserting data .i already have an table with 2 rows of data and i need to add an additional one into it .although everything looks fine i cant able to insert data into table. no error also is showed in console help please folks,thanks in advance
index.html
<html>
<head>
<meta charset="UTF-8">
<title>demo2</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css">
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body style="display: none;">
<!--application UI goes here-->
<h1>Please Enter The Student Details</h1>
<form >
student id:<input type="number" id="stdid" ><br><br>
student name<input type="text" id= "stdname" > <br><br>
<input type="submit" value="Register" onclick="insertValuesToDB();">
</form>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
</body>
</html>
main.js
function wlCommonInit(){
}
function insertValuesToDB(){
var invocationData = {
adapter:"Insertadap",
procedure:"insertvaluesprocedure",
parameters:[$('#stdid').val(),$('#stdname').val()]
};
WL.client.invokeProcedure(invocationData,{
onSuccess :loadFeedsSuccess1,
onFailure :loadFeedsFailure1,
});
}
function loadFeedsSuccess1() {
alert("success");
}
function loadFeedsFailure1() {
alert("failure");
}
adapter.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed Materials - Property of IBM
5725-I43 (C) Copyright IBM Corp. 2011, 2013. All Rights Reserved.
US Government Users Restricted Rights - Use, duplication or
disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
-->
<wl:adapter name="Insertadap"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wl="http://www.ibm.com/mfp/integration"
xmlns:sql="http://www.ibm.com/mfp/integration/sql">
<displayName>Insertadap</displayName>
<description>Insertadap</description>
<connectivity>
<connectionPolicy xsi:type="sql:SQLConnectionPolicy">
<!-- Example for using a JNDI data source, replace with actual data source name -->
<!-- <dataSourceJNDIName>java:/data-source-jndi-name</dataSourceJNDIName> -->
<!-- Example for using MySQL connector, do not forget to put the MySQL connector library in the project's lib folder -->
<dataSourceDefinition>
<driverClass>com.mysql.jdbc.Driver</driverClass>
<url>jdbc:mysql://localhost:****/hello</url>
<user>****</user>
<password>***</password>
</dataSourceDefinition>
</connectionPolicy>
</connectivity>
<!-- Replace this with appropriate procedures -->
<procedure name="insertvaluesprocedure"/>
<procedure name="procedure2"/>
</wl:adapter>
ADAP imp.js
var users = WL.Server.createSQLStatement("INSERT INTO studentdb(stdid,stdname) VALUES(?,?)");
function insertvaluesprocedure(stdid,stdname) {
return WL.Server.invokeSQLStatement({
preparedStatement : users,
parameters : [stdid,stdname]
});
}
When previewing the application in Chrome and Chrome DevTools are open and you use the app - what is the error that you see in the Chrome DevTools console?
Additionally, the error may just be that you declared in the adapter XML a procedure "procedure2", but in your client code you are calling "procedure1".
Change "procedure1" to "procedure2".
Edit: based on the comments it appears to be a type mistmatch.
Assuming the stdid is supposed to correspond to the int field in the database, this will obviously be a problem because in JavaScript by default it is treated as a string.
So you have two options:
In your database, change int to varchar
In your JavaScript, do something like var stdid = stdid * 1;, which should then change it to number, and then it will likely be accepted by the database.

Button click to display a table from mysql in ibm mobile first

I am in process of learning so kindly help me to do how the retrieval of table from mysql in ibm mobile first by just clicking an button from my html page. I have tried but not working help please
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>vikdemodb</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css">
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body style="display: none;">
<!--application UI goes here-->
<div id="header">
<h1>database Demo</h1>
</div>
<div id="wrapper">
<input type="button" id="databasecon" value="click me to get data from db" /><br />
</div>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
</body>
</html>
My main.js
function wlCommonInit(){
$('#databasecon').click(loadSQLRecords);
}
function loadSQLRecords(){
var invocationData = {
adapter : 'vikadap',
procedure : 'getstudinfo',
parameters : []
};
WL.Client.invokeProcedure(invocationData,{
onSuccess : loadSQLQuerySuccess,
onFailure : loadSQLQueryFailure
});
}
function loadSQLQuerySuccess(result){
window.alert("success");
console.log("Retrieve success" + result);
console.log(result.invocationResult.resultSet);
}
function loadSQLQueryFailure(result){
WL.Logger.error("Retrieve failure");
}
You have a button in your HTML:
<input type="button" id="databasecon" value="click me to get data from db" />
You handle this button in wlCommonInit():
$('#databasecon').click(loadSQLRecords);
In loadSQLRecords() you call an adapter procedure to retrieve data from the database. If this operation succeeds then it calls the loadSQLQuerySuccess callback function.
It is this function that you are supposed to handle the display of the response from the backend (your database). But what are you doing? You only print to the console the response. You do not handle at all, displaying it in the application - in the HTML.
So in your HTML, you need to prepare a place holder that you will append the result into. For example: <table id="mytable"></table>
Then you need to populate the table with the data...
So in loadSQLQuerySuccess, you could for example do the following... this is where you need to learn HTML and JavaScript to accomplish what YOU want it to look like:
function loadFeedsSuccess(result) {
if (result.invocationResult.resultSet.length > 0)
displayFeeds(result.invocationResult.resultSet);
else
loadFeedsFailure();
}
function loadFeedsFailure() {
alert ("failure");
}
function displayFeeds(result) {
for (var i = 0; i < result.length; i++) {
$("#mytable").append("<tr><td>" + result[i].firstName + "</td></tr>");
$("#mytable").append("<tr><td>" + result[i].lastName + "</td></tr>");
}
}
Note that you need to create your own code in the for loop to make it look like how you want it to look, and of course append your own properties from the database, instead of "firstName" and "lastName".

Invocation of table from mysql is not working

My adapter works fine but cant able to invoke in client side code. I have created a button and if I click it should display the database table.
Yes I have copied this code from other blog but modified here so need help.
<html>
<head>
<meta charset="UTF-8">
<title>vikdemodb</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css">
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body style="display: none;">
<!--application UI goes here-->
<div id="header">
<h1>database demo</h1>
</div>
<div id="wrapper">
<input type="button" id="databasecon" value="click me to get data from db" /><br />
</div>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
</body>
</html>
my main.js
function wlCommonInit(){
$('#databasecon').click(loadSQLRecords);
}
function loadSQLRecords(){
var invocationData = {
adapter : 'vikadap',
procedure : 'getstudinfo',
parameters : []
};
WL.Client.invokeProcedure(invocationData,{
onSuccess : loadSQLQuerySuccess,
onFailure : loadSQLQueryFailure
});
}
function loadSQLQuerySuccess(result){
console.log("Retrieve success" + result);
console.log(result.invocationResult.resultSet);
}
function loadSQLQueryFailure(result){
WL.Logger.error("Retrieve failure");
}
My adapter implementation
var procedure1Statement = WL.Server.createSQLStatement("select * from studentinfo");
function getstudinfo() {
return WL.Server.invokeSQLStatement({
preparedStatement : procedure1Statement,
parameters : []
});
}
here my adap.xml
<wl:adapter name="vikadap"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wl="http://www.ibm.com/mfp/integration"
xmlns:sql="http://www.ibm.com/mfp/integration/sql">
<displayName>vikadap</displayName>
<description>vikadap</description>
<connectivity>
<connectionPolicy xsi:type="sql:SQLConnectionPolicy">
<!-- Example for using a JNDI data source, replace with actual data source name -->
<!-- <dataSourceJNDIName>java:/data-source-jndi-name</dataSourceJNDIName> -->
<!-- Example for using MySQL connector, do not forget to put the MySQL connector library in the project's lib folder -->
<dataSourceDefinition>
<driverClass>com.mysql.jdbc.Driver</driverClass>
<url>jdbc:mysql://localhost:***/***</url>
<user>****</user>
<password>****</password>
</dataSourceDefinition>
</connectionPolicy>
</connectivity>
<procedure name="getstudinfo"/>
I must say that this is quite sad. You copy the entire "implementation" from elsewhere, but do not copy the one thing that will finish it - displaying the data that is retrieved by the adapter. Then, you ask a question how to do it... I don't know what is your end goal with your project, but I don't think you'll get there if you will continue like this.
One way you could display the result is a function like this:
function displayFeeds(items){
var ul = $('#itemsList');
for (var i = 0; i < items.length; i++) {
var li = $('<li/>').html(items[i].sid);
li.append($('<li/>').html(items[i].sname));
li.append($('<li/>').html(items[i].sgrade));
li.append($('<hr>'));
ul.append(li);
}
}
This function assumes there is a UL in your HTML, and then appends LI's into it with items.
You will need to change this to fit your table design, as well as change sid, sname and sgrade with the correct property names from your database.
Next time you copy, at least copy everything: http://javatechig.com/ibm-worklight/invoking-adapter-procedure-in-ibm-worklight

How to use an Observable object in a WinJS ListView

I want to use an observable object within a ListView in the Windows 8 RT (Developer Preview from BUILD 2011) (using JavaScript).
The code below seems like it should work. It has a simple template for displaying a title and a description of each object in the HTML and a basic use of the WinJS.UI.Listview component.
I expect to see a list of objects, but always see the "wait spinner" when the list contains observables.
Experimentally, I've noticed that if the code doesn't convert the entire list (all but 3) to observables, then the list will show up. From doing some debugging, it would appear that it's somehow timing related and that the WinJS framework miscounts and fails to render the ListView entirely (as some of the objects are "pending") for some reason (the miscount confusion happens deep in a call to realizeItems in the ScrollView code). If I comment out the enableFirstChanceException function call, it fails while comparing two objects (but I don't know if it's relevant) in the function itemChanged (circular reference in value argument not supported).
Any idea on how to make this work with observable objects?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=1024, height=768" />
<title>WinWebApp1</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script type="text/javascript" src="/WinJS/js/base.js"></script>
<script type="text/javascript" src="/WinJS/js/ui.js"></script>
<script type="text/javascript" src="/WinJS/js/binding.js"></script>
<script type="text/javascript" src="/WinJS/js/controls.js"></script>
<script type="text/javascript" src="/WinJS/js/res.js"></script>
<script type="text/javascript" src="/WinJS/js/animations.js"></script>
<script type="text/javascript" src="/WinJS/js/uicollections.js"></script>
<script type="text/javascript" src="/WinJS/js/wwaapp.js"></script>
<!-- WinWebApp1 references -->
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
</head>
<body>
<div id="itemTemplate" data-win-control="WinJS.Binding.Template" >
<div class="itemContainer">
<!-- Displays the "title" field. -->
<div class="itemTitle" data-win-bind="innerText: title">
</div>
<!-- Displays the "description" field. -->
<div class="itemDescription" data-win-bind="innerText: description">
</div>
</div>
</div>
<div data-win-control="WinJS.UI.ViewBox">
<div class="fixed-layout">
<div id="basicListView" data-win-control="WinJS.UI.ListView" data-win-options="{itemRenderer: itemTemplate}">
</div>
</div>
</div>
</body>
</html>
And the JavaScript:
(function () {
'use strict';
// Uncomment the following line to enable first chance exceptions.
//Debug.enableFirstChanceException(true);
var myData = [
{ title: "Banana", description: "Banana Frozen Yogurt"},
{ title: "Orange", description: "Orange Sherbet"},
{ title: "Vanilla", description: "Vanilla Ice Cream"},
{ title: "Mint", description: "Mint Gelato"},
{ title: "Strawberry", description: "Strawberry Sorbet"},
{ title: "Kiwi", description: "Kiwi Sorbet" }
];
// this works:
//var myDataSource = new WinJS.UI.ArrayDataSource(myData);
// this does not:
for (var i = 0; i < myData.length ; i++) {
myData[i] = WinJS.Binding.as(myData[i]);
}
var myDataSource = new WinJS.UI.ArrayDataSource(myData);
document.addEventListener("DOMContentLoaded", function (e) {
WinJS.UI.processAll()
.then(function () {
var basicListView = WinJS.UI.getControl(document.getElementById("basicListView"));
basicListView.dataSource = myDataSource;
// when the observable works correctly, this should work (and live change the list)
//setTimeout(function () {
// basicListView.refresh();
// myData[0].title = "Yellow Banana";
// myData[5].title = "Kiwisicle";
//}, 3000);
});
});
WinJS.Application.start();
})();