Insertion of values in database - ibm-mobilefirst

Hey I am using IBM Worklight V6.2.I want to insert values into database
My Html Code is
<h1>Please Enter The Car Details</h1>
<form >
Car No:<input type="number" id="carnum" placeholder="Please enter your no" ><br><br>
Details:<input type="text" id= "details" placeholder="Please enter car details" > <br><br>
<input type="submit" value="Register" onclick="loadFeeds1()">
</form>
My procedure is:
var users = WL.Server.createSQLStatement("insert into car(carno,details) values (?,?)");
function getusers(carno,details) {
return WL.Server.invokeSQLStatement({
preparedStatement : users,
parameters : [carno,details]
});
}
My js file is this
function loadFeeds1(){
var invocationData = {
adapter:"car2",
procedure:"getuser",
parameters:["carno","details"]
};
WL.Server.invokeProcedure(invocationData,{
onSuccess :loadFeedsSuccess1,
onFailure :loadFeedsFailure1,
});
}
function loadFeedsSuccess1() {
WL.Logger.debug("inserted");
}
function loadFeedsFailure1() {
WL.Logger.debug("failed");
}
I am able to invoke procedure from adapter..but not able to see when i insert values in browser.not it is showing anything in console..Kindly suggest...

You can't simply place the IDs of your inputs as the WL.client.invokeProcedure's parameters... You need to pass their value.
For example:
function loadFeeds1(){
var invocationData = {
adapter:"car2",
procedure:"getuser",
parameters:[$('#carnum').val(),$('#details').val()]
};
WL.Server.invokeProcedure(invocationData,{
onSuccess :loadFeedsSuccess1,
onFailure :loadFeedsFailure1,
});
}
This is an end-to-end scenario, where I take 2 values from the HTML and insert them into the database. To re-create, you can you use the WorklightTraining.sql scheme provided in the Adapters sample project. You can see it works because after the 'success', if you will refresh the database - you'll see the new record.
HTML:
<h1>Test Insert Into Database</h1>
<input type="text" id="value1" placeholder="value1"/><br/>
<input type="text" id="value2" placeholder="value2"/><br/>
<input type="button" value="Insert values to database" onclick="insertValuesToDB();"/>
main.js:
function insertValuesToDB() {
var invocationData = {
adapter: 'insertValuesAdapter',
procedure: 'insertValuesProcedure',
parameters: [$('#value1').val(), $('#value2').val()]
};
WL.Client.invokeProcedure(invocationData, {onSuccess: insertSuccess, onFailure: insertFailure});
}
function insertSuccess() {
alert("success");
}
function insertFailure() {
alert("failure");
}
Adapter XML:
...
...
<connectivity>
<connectionPolicy xsi:type="sql:SQLConnectionPolicy">
<dataSourceDefinition>
<driverClass>com.mysql.jdbc.Driver</driverClass>
<url>jdbc:mysql://localhost:3306/worklight_training</url>
<user>Worklight</user>
<password>Worklight</password>
</dataSourceDefinition>
</connectionPolicy>
<loadConstraints maxConcurrentConnectionsPerNode="5" />
</connectivity>
<procedure name="insertValuesProcedure"/>
...
...
Adapter implementation:
var insertValuesProcedureStatement = WL.Server.createSQLStatement("INSERT INTO users(userId, firstName, lastName, password) VALUES (?,?, 'someLastName', 'somePassword')");
function insertValuesProcedure(value1,value2) {
return WL.Server.invokeSQLStatement({
preparedStatement : insertValuesProcedureStatement,
parameters : [value1,value2]
});
}

Related

Passing value from textbox to http adapter failed mobilefirst platform

I'm trying to pass some values from a textbox to an http adapter and it have the following error:
Here is the index.html
Username:<br>
<input type="text" name="username" id="username"><br>
Password:<br>
<input type="text" name="password" id="password"><br>
<button onclick="mobgetVerify()">Login</button>
<p>
<p id="demo"></p> <br />
<br />
<br />
mains.js
function mobgetVerify() {
alert("Hi" + $('#username').val() + $('#password').val());
var invocationData = {
adapter : 'LoginAdapter',
procedure : 'getVerify',
parameters : [ $('#username').val() , $('#password').val() ]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : getVerifySuccess,
onFailure : getVerifyFailure,
});
};
function getVerifySuccess(res) {
var httpStatusCode = res.status;
if (200 == httpStatusCode) {
var invocationResult = res.invocationResult;
var isSuccessful = invocationResult.isSuccessful;
if (true == isSuccessful) {
$("#demo").html(JSON.stringify(res.responseJSON.data));
if (res.responseJSON.data== "True "){
window.location="pages/view.html";
}
alert("Success: Value= " + res.responseJSON.data);
} else {
alert("Error. isSuccessful=" + isSuccessful);
}
} else {
alert("Error. httpStatusCode=" + httpStatusCode);
}
};
function getVerifyFailure(result){
alert("Verification Failure");
};
I would highly appreciate if i can get some help. Thank you.
The provided sample application worked just fine... I received an alert dialog with the text: "Success: Value=False".
The only difference I can think of, which relates every time in each of your questions... if the IP address. In your provided LogCat, it shows the server's IP address is "10.0.0.3", whereas mine is my actual IP address (9.148.x.y in my case).
As you were previously advised - use the correct IP address of the server in wlclient.properties.
To check for mine, I typed the following in Terminal: ifconfig (in Windows - "ipconfig").

SAPUI5 sap.m.Input - Suggestion values

How do I enable live suggestions with reading from my odata Service for a single cell in my table?
oTable.addColumn(new sap.ui.table.Column({
template : new sap.m.Input({
value : column, // also works, its dynamic
textAlign : sap.ui.core.TextAlign.Center,
inputType : Text,
type : sap.m.InputType.Text,
showSuggestion : true,
liveChange : function() {
if (this.getValue().length > 0) {
var oModel = new sap.ui.model.json.JSONModel();
var value = this.getValue();
var serviceUrl = "/sap/opu/odata/SAP/XXXX_SRV/SuggestionsSet/?$filter=startswith(Key,'" + value + "')";
oModel.loadData(serviceUrl, null, false, "GET", false, false, null);
this.destroySuggestionItems();
for (var i = 0; i < oModel.oData.d.results.length; i++) {
this.addSuggestionItem(new sap.ui.core.Item({
text: oModel.oData.d.results[i].Key,
}));
} // everything seems fine, but no Suggestion opens..
}
},
}),
visible : true,
}));
See the explored example.
However, in your case the model is an ODataModel, but that does not really matter...
As you can see in the examples's code you can also use
showSuggestion="true"
suggest="handleSuggest"
suggestionItems="{/ProductCollection}"
In the handler you then do this (copied from the example as well):
handleSuggest: function(oEvent) {
var sTerm = oEvent.getParameter("suggestValue");
var aFilters = [];
if (sTerm) {
aFilters.push(new Filter("Name", sap.ui.model.FilterOperator.StartsWith, sTerm));
}
oEvent.getSource().getBinding("suggestionItems").filter(aFilters);
}
Basically you
- create one or more filters
- get the binding for the suggestionItems aggregation
- call .filter(...) on the binding and pass the filter(s)
There is no need to code that stuff manually (i.e. GET request etc.).
Here is a runninh example for you (run via jsbin), see below.
In your case all you do is bind to
suggestionItems="{path:'/SuggestionSet', templateShareable:false}">
In the handleSuggest handler you would then get the the value for the Key property of the SuggestionSet that belongs to current/corresponding input field in order to instantiate a new Filter. You could get the Key from the BindingContext I guess...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>SAPUI5 single file template | nabisoft</title>
<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.m"
data-sap-ui-bindingSyntax="complex"
data-sap-ui-compatVersion="edge"
data-sap-ui-preload="async"></script>
<!-- use "sync" or change the code below if you have issues -->
<!-- XMLView -->
<script id="myXmlView" type="ui5/xmlview">
<mvc:View
controllerName="MyController"
xmlns="sap.m"
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc">
<Table
id="myTable"
growing="true"
growingThreshold="10"
growingScrollToLoad="true"
busyIndicatorDelay="0">
<columns>
<Column>
<Text text="Customer ID"/>
</Column>
<Column>
<Text text="Company Name"/>
</Column>
</columns>
<items>
<!-- filled via bindItems() in controller -->
</items>
</Table>
</mvc:View>
</script>
<!-- XML Fragment -->
<script id="myXMLFragment" type="ui5/fragment">
<core:FragmentDefinition
xmlns="sap.m"
xmlns:core="sap.ui.core">
<ColumnListItem type="Active">
<cells>
<ObjectIdentifier title="{CustomerID}"/>
<Input
value="{CompanyName}"
showSuggestion="true"
suggest="handleSuggest"
suggestionItems="{path:'/Customers', templateShareable:false}">
<suggestionItems>
<core:Item text="{CompanyName}" />
</suggestionItems>
</Input>
</cells>
</ColumnListItem>
</core:FragmentDefinition>
</script>
<script>
sap.ui.getCore().attachInit(function () {
"use strict";
//### Controller ###
sap.ui.controller("MyController", {
onInit : function () {
this.getView().setModel(
new sap.ui.model.odata.v2.ODataModel("https://cors-anywhere.herokuapp.com/services.odata.org/V2/Northwind/Northwind.svc/", {
json : true,
useBatch : false
})
);
var sPath = "/Customers";
var oTable = this.byId("myTable");
var oTemplate = sap.ui.xmlfragment({
fragmentContent : jQuery("#myXMLFragment").html()
});
oTable.bindItems(sPath, oTemplate, null /*oSorter*/, null /*aFilters*/);
},
handleSuggest: function(oEvent) {
var sTerm = oEvent.getParameter("suggestValue");
var aFilters = [];
if (sTerm) {
aFilters.push(new Filter("CompanyName", sap.ui.model.FilterOperator.StartsWith, sTerm));
}
oEvent.getSource().getBinding("suggestionItems").filter(aFilters);
}
});
//### THE APP: place the XMLView somewhere into DOM ###
sap.ui.xmlview({
viewContent : jQuery("#myXmlView").html()
}).placeAt("content");
});
</script>
</head>
<body class="sapUiBody">
<div id="content"></div>
</body>
</html>

AutoComplete Textbox with database

I wanna do autocomplete when i enter a letter.
I have a database "USERS" and it has name .When i try texted for example e
it must show "edgar,edwin,emir" but ,t shows nothing.
ClientController here:
public class ClientController : Controller
{
public JsonResult AutocompleteSuggestions(string searchstring)
{
ModelContext db = new ModelContext();
var suggestions = from E in db.USERS
select E.Name;
var namelist = suggestions.Where(n => n.ToLower().Contains(searchstring.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
}
index.cshtml here:in here there is a textbox and i send client controller autocopleteSuggeston method but it doesnt go or it doesnt work.I add jquery script file on cshtml but it still not working.
#using (Html.BeginForm())
{
<p>
Name: #Html.TextBox("SearchString")
<input type="submit" value="Search" />
</p>
}
<script type="text/javascript">
window.jQuery(function () {
window.jQuery("#SearchString").autocomplete({
source: "/Client/AutocompleteSuggestions",
minLength: 1,
select: function (event, ui) {
if (ui.item) {
window.jQuery("#SearchString").val(ui.item.value);
window.jQuery("form").submit();
}
}
});
});
</script>
i add jquery
Where is the mistake?
you need to add [HttpPost] before JsonResult method like this:
[HttpPost]
public JsonResult AutocompleteSuggestions(string searchstring)
{
ModelContext db = new ModelContext();
var suggestions = from E in db.USERS
select E.Name;
var namelist = suggestions.Where(n => n.ToLower().Contains(searchstring.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
as the form here is submitted using window.jQuery("form").submit(),it invokes a Post Action, so you need to add [HttpPost] for capturing the form submissions or any kind of Post Action!
Change your View Code to
#using( Html.BeginForm(null, null, FormMethod.Post, new{#id ="SearchForm"} ))
{
<p>
Name: #Html.TextBox("SearchString")
<input type="submit" value="Search" />
</p>
}
$(function() {
$("#SearchString").autocomplete({
source: "/Client/AutocompleteSuggestions",
select: function(event, ui) {
$("#SearchString").val(ui.item.value);
$("#SearchForm").submit();
}
});
});

Aurelia Validation validation error detected, but no error message

I have a super simple code I'm trying to validate:
<template>
<form role="form" submit.delegate="submit()" validate.bind="validation">
<div class="form-group">
<label>Test Field</label>
<input type="text" value.bind="testField" class="form-control" validate="Description" placeholder="What needs to be done?" />
<button type="submit">Submit</button>
</div>
</form>
</template>
With the following viewmodel
define(["require", "exports", "../scripts/HttpClient", "aurelia-validation", "aurelia-framework"], function(require, exports, HttpClient) {
var AureliaValidation = require('aurelia-validation').Validation;
var MyViewModel = (function () {
function MyViewModel(httpClient, aureliaValidation, isReadyCallback) {
this.httpClient = httpClient;
var self = this;
self.setupValidation(aureliaValidation);
}
MyViewModel.prototype.activate = function (params, queryString, routeConfig) {
};
MyViewModel.prototype.setupValidation = function (validation) {
this.testField = "";
this.validation = validation.on(this).ensure('testField');
//validation
// .on(this.serviceMetadata.ServiceData[0])
// .ensure('Value');
this.validation = this.validation.notEmpty().maxLength(3);
};
MyViewModel.prototype.submit = function () {
debugger;
if (this.validation.checkAll()) {
//Do Something
}
return null;
};
MyViewModel.inject = [HttpClient, AureliaValidation];
return MyViewModel;
})();
return MyViewModel;
});
Now I got it working for the most part, and the validation is showing false on submit check, the textbox outline color changes etc., however it's not injecting the validation error messages into the DOM. There's no script error message either, how can I troubleshoot this?
Yes, I can see the validation messages in the validationProperties, but they're not written to the UI.
If your browser allows it, find the JSPM packages in the sources and put a breakpoint here, it's the point where the view strategy looks for labels to append error messages to. If you'd have this code in the open, I'd be happy to have a look for you.
Also, what version of aurelia/aurelia-validation are you using?
And finally, did you modify your sample before posting?
`<input value.bind="testField" validate="Description" />`
These two attributes are contradictory. It binds the value to testField, but then you use the validate attribute to explicitly show validation messages for property "Description".

Pass ViewModel back to controller

I have a working application integrating Bootstrap and Knockout. This app pulls data from my controller and displays this in the UI as I would expect. I can see values are updated when I click or change a value but I can't seem to see that data passed back to my controller for the purposes of saving it. All I need to know is how to fix what I have to allow me to pass the selectedRequestorName back to the controller.
Here is a sample class
public class Requestor
{
public int Id { get; set; }
public string Name { get; set; }
}
Interface
interface IRequestorRepository
{
IList<Requestor> GetAllRequestors();
}
Here is the repository with the seed data
public class RequestorRepository : IRequestorRepository
{
private List<Requestor> requestors = new List<Requestor>();
private int _nextId = 1;
public RequestorRepository()
{
Add(new Requestor{ Id = 1, Name = "Brian" });
Add(new Requestor { Id = 2, Name = "Steve" });
Add(new Requestor { Id = 3, Name = "Jake" });
}
public IList<Requestor> GetAllRequestors()
{
return requestors;
}
public Requestor Add(Requestor item)
{
if (item == null)
{
throw new ArgumentNullException("Null Requestor");
}
item.Id = _nextId++;
requestors.Add(item);
return item;
}
}
My HomeController looks like the following
public class HomeController : Controller
{
static readonly IRequestorRepository req_repository = new RequestorRepository();
// GET: /Home/
public ActionResult Index()
{
ViewBag.DateNow = DateTime.Now.ToShortDateString();
return View();
}
public JsonResult GetRequestors()
{
return Json(req_repository.GetAllRequestors(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult SaveDetails(Requestor selectedRequestorName)
{
int id = -1;
return Json(id, "json");
}
}
In my Index.cshtml I have the following in a script tag at the top of the page
// Global variable
var viewModel = null;
$(document).ready(function () {
function ViewModel() {
//Make the self as 'this' reference
var self = this;
// Requestors
self.RequestorId = ko.observable("");
self.RequestorName = ko.observable("");
self.RequestorSourceDatabase = ko.observable("");
var RequestorNames = {
Id: self.RequestorId,
Name: self.RequestorName,
SourceDatabase: self.RequestorSourceDatabase
};
self.selectedRequestorName = ko.observable();
self.RequestorNames = ko.observableArray(); // Contains the list of RequestorNames
// Initialize the view-model for Requestors
$.ajax({
url: '#Url.Action("GetRequestors", "Home")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.RequestorNames(data);
}
});
// END Requestors
// Reset
self.reset = function () {
self.Name("");
}
// Cancel
self.cancel = function () {
self.Name(null);
}
}
viewModel = new ViewModel();
ko.applyBindings(viewModel);
});
$(function () {
$('#Save').click(function (e) {
// Check whether the form is valid. Note: Remove this check, if you are not using HTML5
if (document.forms[0].checkValidity()) {
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("SaveDetails", "Home")',
data: ko.toJSON(viewModel.selectedRequestorName),
contentType: 'application/json; charset=utf-8',
async: true,
beforeSend: function () {
// Display loading image
},
success: function (result) {
if (result > 0) {
alert("This work request has been successfully saved in database. The Document ID is: " + result);
} else {
alert("The Work Request was not saved, there was an issue.");
}
},
complete: function () {
// Hide loading image.
},
error: function (jqXHR, textStatus, errorThrown) {
// Handle error.
}
});
}
else {
alert("Form is not valid");
}
});
});
And finally the control that contains the displayed data for the user to select from...
<p>Current selection is <span data-bind="text:selectedRequestorName"></span></p>
<!-- Requestors -->
<div class="input-group col-sm-8">
<input type="text" data-bind="value:selectedRequestorName" class="form-control item" placeholder="Requestor Name" name="Requestor">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle item" data-toggle="dropdown">Select <span class="caret"></span></button>
<ul class="dropdown-menu" data-bind="foreach: RequestorNames">
<li class="dropdown">
</li>
</ul>
</div>
</div>
<div>
<button id="Save" type="submit" class="btn btn-default btn-success">Create</button>
</div>
create an action method on your controller that accepts an selectedRequestorName (string?) as argument.
create a function in your knockout viewmodel that reads the selectedRequestorName from the ko vm, JsonStringify it and pass it back to the above action method via ajax.
[HttpPost]
public JsonResult SaveDetails(String selectedRequestorName)
{
int id = -1;
return Json(id, "json");
}
change type of selectedRequestorName to String from Requestor as above that should work.
note not tested.but let me know if it helps.
Within $('#Save').click(), would you please change the line
data: ko.toJSON(viewModel.selectedRequestorName)
with
data: ko.toJSON(viewModel.selectedRequestorName())
hope, this will help.