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

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)

Related

Failing to send Email (Mailtrap) with Laravel 9 , by getting data from Vue.js 3 component , with Axios

Hello when i get some data on my Vue app (from 2 forms, 1 select and 1 table), i want to click a button to send that data to the email put on the respective form. With my code, i am able to show the data i want to send, in a output i create on my app, as testing, however no mail is sent. My .env file is filled correctly and here are my other files
I created a mailable ComprasMail
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class ComprasMail extends Mailable
{
use Queueable, SerializesModels;
public $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$subject = 'Compra Efectuada com Sucesso';
return $this->view('Email.comprasMail')->subject($subject);
}
}
I created a blade file por my mail template
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght#400;600;700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Material+Icons"rel="stylesheet">
<link rel="shortcut icon" href="/img/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" href="/img/apple-touch-icon.png">
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght#400;600;700&display=swap" rel="stylesheet">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="/css/bootstrap.min.css">
<!-- Site CSS -->
<link rel="stylesheet" href="/css/style.css">
<!-- ALL VERSION CSS -->
<link rel="stylesheet" href="/css/versions.css">
<!-- Responsive CSS -->
<link rel="stylesheet" href="/css/responsive.css">
<!-- Custom CSS -->
<link rel="stylesheet" href="/css/custom.css">
<link rel=”stylesheet” href=”https://cdn-uicons.flaticon.com/uicons-regular-rounded/css/uicons-regular-rounded.css”>
<!-- Modernizer for Portfolio -->
<script src="/js/modernizer.js"></script>
</head>
<body>
<tr>
<div id="hosting" class="section wb" style="background: rgb(248, 248, 248)">
<br>
<br>
<table cellpadding="0" height="100" width="100%">
<tr>
<td text-align="center" valign="top" class="email-container">
<div>
<td text-align='center' style='text-align:center'><a href="http://127.0.0.1:8000/home" target="_blank">
</div>
<br>
<div class="row dev-list ">
<div class="col-lg-4 col-md-4 col-sm-12 col-xs-12 wow fadeIn" data-wow-duration="1s" data-wow-delay="0.3s">
<div class="wow fadeIn" text-align="center" style="background-color: rgba(0, 0, 0, 0.10); border-radius: 15px;" data-wow-duration="1s" data-wow-delay="0.3s">
<br>
<div class="message-box">
<div class="widget-title">
<h3 style="color: #E62B36; font-family: Eczar;"><strong>Bom dia caro {{$data['nome']}}</strong></h3>
<h4 text-align="center"> {{$data['transportadora']}} </h4>
</div>
<!-- end title -->
</div>
<hr>
<h6 text-align="center"> © {{ date('Y') }} Desafio Tecnico. Todos os Direitos Reservados</h6>
<br>
<br>
</div>
<!--widget -->
<br>
</div><!-- end col -->
</div><!-- end row -->
</tr>
</table>
</div><!-- end container -->
Here is my route
Route::post('/mail-send', [ProdutoController::class, 'mailSend']);
In my controller ( when i tried the return response that is commented, i simply have a 500 error)
public function mailSend(Request $request) {
return response()->json([$request->all()]);
$email = $request->email;
$data = [
'name' => $request->nome,
'transportadora' => $request->transportadora
];
Mail::to($email)->send(new ComprasMail($data));
/* return response()->json([
'message' => 'Mail has sent.'
], Response::HTTP_OK);*/
}
In my vue component, first the button
<button :disabled="isDisabled2" #click="sentMail"> Add </button>
my data()
data() {
return{
compras:[],
nome:"",
email:"",
transportadora:"",
output:"",
My sentMail function
sentMail(e) {
e.preventDefault();
var obj = this;
axios.post('/mail-send', {
nome: this.nome,
email: this.email,
transportadora: this.transportadora,
compras: this.compras
}).then(function (response) {
obj.output = response.data;
})
.catch(function (error) {
obj.output = error;
});
},
With this , as i said, all the data i want to collect is correctly saved, and appear how it is expected when i call the obj.output. However i am not able to send any email . First i am trying to send emails with only the name, to see if it works, then after that i will put more on the template.
Thank you in advance
Edit: Just did this tutorial as a way to test if i at least could send a simple email and it worked, so at least i know now my problem it is not with the config with Mailtrap and it is somewhere inside my code
https://www.youtube.com/watch?v=WU4_HzTa6PM
Edit 2: Made some changes on the code,but still won't work. After some testing i concluded that my Mailable, and config are correct, since with the small tutorial i used for testing, it worked, however i am not understanding why the mail i set up isn't being sent
I would appreciate any kind of help. Thank You
Just more update. The error that is giving me on the console is:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
settle.js:19 Uncaught (in promise)
AxiosError
code
:
"ERR_BAD_RESPONSE"
config
:
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
:
"Request failed with status code 500"
name
:
"AxiosError"
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response
:
{data: {…}, status: 500, statusText: 'Internal Server Error', headers: AxiosHeaders, config: {…}, …}
stack
:
"AxiosError: Request failed with status code 500\n at settle (http://[::1]:5173/node_modules/.vite/deps/axios.js?v=600aa94f:1116:12)\n at XMLHttpRequest.onloadend (http://[::1]:5173/node_modules/.vite/deps/axios.js?v=600aa94f:1327:7)"
[[Prototype]]
:
Error
After several time looking dor a solution to my problem, i finally was able to find one. In my Script i simply needed to change error to error.response.data For some reason, with only «error» it was always giving a 500 error
sentMail(e) {
e.preventDefault();
var obj = this;
axios.post('/mail-send', {
nome: this.nome,
mail: this.email,
transportadora: this.transportadora,
compras: this.compras
}).then(function (response) {
obj.output = response.data;
})
.catch(function (error) {
obj.output = error;
});
},

vue.js2 console err is "app.js:2 Uncaught SyntaxError: Unexpected identifier"

the result should be a paragraph contain a name and button to change this name
from "adel" to "mohamed" but it is not working ,not showing any thing in the browser and i have console err is:
app.js:2 Uncaught SyntaxError: Unexpected identifier,
You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html
html code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue.js course</title>
<link rel="stylesheet" href="./styles.css">
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="vue-app-one">
<greeting></greeting>
</div>
<div id="vue-app-two">
<greeting></greeting>
</div>
<script src="./app.js"></script>
</body>
</html>
app.js code
Vue.component('greeting', {
template: "<h1>hello {{ name }}. <button v-on:click="chang">change name</button></h1>",
data(){
return {
name:"adel"
}
},
methods: {
chang: function(){
this.name = 'mohamed';
}
}
});
var one = new Vue({
el: '#vue-app-one'
});
var two = new Vue({
el: '#vue-app-two'
});
It's simple. Just change the double quotation marks used in template to single quotation marks.
you can't include the same quote mark inside the string if it's being used to contain them
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Strings
template: "<h1>hello {{ name }}. <button v-on:click="chang">change name</button></h1>",
to
template: "<h1>hello {{ name }}. <button v-on:click='chang'>change name</button></h1>",
jsfiddle that works

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".

Http Adapter Invocation failure?

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

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();
})();