Sending form data to spring controller using dojo - json

I've a list of records and want to update one. When I click on one, it show a form with all input fields which are already populated using JsonRest. I've edited the fields and now I want to send it to server for updating.
How can I send an Object with dojo?
I tried like this, but at the controller side the value is null.
on(dom.byId("poolForm"), "submit", function(evt) {
var formObj = domForm.toObject("poolForm");
console.log(formObj);
request.post("/path/to/EditSubmit", {
data : formObj,
method : "POST"
}). then(function(data) {
console.log("data");
});
});
In spring I used:
public void editedForm(HttpServletResponse response, #RequestBody MyClass myClass) {
poolParam.getAdd();
}

Assuming you are creating a new record and not updating one, you can use method add(object, options) for your JsonRest.
Example:
require(["dojo/store/JsonRest"], function(JsonRest){
// your store
var store = new JsonRest({
target: "/some/resource"
});
// add an object passing an id
store.add({
foo: "foo"
}, {
id: 1
});
});
More informations can be found at JsonRest API and JsonRest guide.
EDIT:
As for your comment request, in case you would like to send an object using dojo/request/xhr instead of JsonRest, you can use the following example, basically:
Use dojo/dom-form utility, to get out values from your form. This utility function will return an object. More info here.
Use dojo/request/xhr to send via Ajax the object previously retrieved from dojo/dom-form, this is the data sent to the server. More info here.
Quick demo here:
https://jsbin.com/mocoxuhotu/edit?html,output
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dijit/themes/claro/claro.css">
<script data-dojo-config="async: 1" src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<script>
require([
"dojo/query",
"dojo/dom-form",
"dojo/request/xhr",
"dijit/registry",
"dijit/form/Form",
"dojo/parser",
"dojo/domReady!"
], function (
query,
domForm,
xhr,
registry,
Form,
parser
) {
var form = new Form({}, 'myForm');
query("a.myLink").on("click", function () {
var data = domForm.toObject(form.domNode);
xhr.post("/echo/json", {
data: data // data to transfer
}).then(function () {
console.log("Success");
});
});
});
</script>
</head>
<body class="claro">
<form data-dojo-type="dijit/form/Form" id="myForm">
<fieldset>
<ul>
<li>
<label for="name">Name:</label>
<input type="text" name="name" />
</li>
<li>
<label for="firstname">First name:</label>
<input type="text" name="firstname" />
</li>
</ul>
</fieldset>
</form>
<a class="myLink">Submit the form</a>
</body>
</html>

Related

How to get jquery autocomplete to display only email addresses that begin with the typed query? [duplicate]

This question already has answers here:
jQuery UI Autocomplete use startsWith
(6 answers)
Closed 2 years ago.
Context
I'm using autocomplete function to search through 360 or more client email address.
I want it to only suggest addresses that begin with the letters typed in by the user.
For example, if the user types "thomas" the function should return suggestions that begin with "thomas" were as at the moment it shows matches which have the word Thomas anywere in their name.
Question
How can I modify either jquery to make sure that items that begin with whats being typed in are returned?
<div class="ui-widget"> </div>
</fieldset>
</form>
<p> </p>
<meta charset="utf-8" />
<meta content="width=200, initial-scale=1" name="viewport" />
<title></title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script><script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script><script>
$( function() {
var availableTags = [
"testemail#yahoo.co.uk, ",
"helloemail#gmail.co.uk, ",
];
$( "#tags" ).autocomplete({
source: availableTags
});
$( "#tags" ).autocomplete("option", "position",
{ my : "right-1 top+35", at: "right top" })
$( "#tags" ).autocomplete({
minLength:4,
source: availableTags
});
} );
</script>
<p><label for="tags">Emails: </label>
<input id="tags" maxlength="120" size="80" type="text" /></p>
<style>
input[type='text'] { font-size: 24px; }
</style>
<div class="ui-widget"> </div>
You can define your own filtering within the Source option.
The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
See more: https://api.jqueryui.com/autocomplete/#option-source
With your example, this could be something like the following.
$(function() {
var myData = [
"smith#matrix.net",
"testemail#yahoo.co.uk",
"helloemail#gmail.co.uk",
"homer#simpsons.tv"
];
$("#tags").autocomplete({
minLength: 4,
source: function(req, resp) {
var results = [];
$.each(myData, function(i, el) {
if (el.indexOf(req.term) == 0) {
results.push(el);
}
});
resp(results);
},
position: {
my: "right-1 top+35",
at: "right top"
}
});
});
input[type='text'] {
font-size: 24px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>
<label for="tags">Emails:</label>
<input id="tags" maxlength="120" size="80" type="text" />
</p>
This uses the .indexOf() to identify the position. So if you want to see if the Term is at the beginning, the position would be 0.
You may want to adjust your minLength incase there is an email like jt#universal.com

Error: Argument 'TodoListController' is not a function, got undefined

Please please help!!!
I have simple program but keep getting error. I dont know if i have to define any .js file in manifest.angular as well??
i have seen people sharing examples from old angularjs. so please help. I have got assignment to do. Thanks
todo.js
angular.module('todoApp', [])
.controller('TodoListController', function () {
var todoList = this;
todoList.todos = [
{ text: 'learn AngularJS', done: true },
{ text: 'build an AngularJS app', done: false }];
todoList.addTodo = function () {
todoList.todos.push({ text: todoList.todoText, done: false });
todoList.todoText = '';
};
todoList.remaining = function () {
var count = 0;
angular.forEach(todoList.todos, function (todo) {
count += todo.done ? 0 : 1;
});
return count;
};
todoList.archive = function () {
var oldTodos = todoList.todos;
todoList.todos = [];
angular.forEach(oldTodos, function (todo) {
if (!todo.done) todoList.todos.push(todo);
});
};
});
index.html:
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<script src="/App_Plugins/TheDashboard/backoffice/HomeDashboard/todo.js"></script>
<link rel="stylesheet" href="/App_Plugins/TheDashboard/backoffice/HomeDashboard/todo.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/css/bootstrap-combined.min.css">
</head>
<body>
<h2>Todo</h2>
<div ng-controller="TodoListController as todoList">
<span>{{todoList.remaining()}} of {{todoList.todos.length}} remaining</span>
[ archive ]
<ul class="unstyled">
<li ng-repeat="todo in todoList.todos">
<label class="checkbox">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</label>
</li>
</ul>
<form ng-submit="todoList.addTodo()">
<input type="text" ng-model="todoList.todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
</body>
</html>
Blockquote
Console Error:
jquery.min.js?cdv=1:4 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
angular.min.js?cdv=1:63 Error: Argument 'TodoListController' is not a function, got undefined
WARNING: Tried to load angular more than once.
angular.js:34191 Uncaught TypeError: window.angular.$$csp is not a function
at angular.js:34191
Blockquote
This will happen in Umbraco when you try and bootstrap two angular modules. Umbraco has the main parent module that you will then want to bootstrap your application separately. If you don't want to do this you can just reference the Umbraco module.
angular.module("umbraco") instead of angular.module('todoApp', []).
Here is a good reference to get started just building property editors https://our.umbraco.org/documentation/Tutorials/Creating-a-Property-Editor/.

AJAX return from SmartyStreets API

I am having trouble actually returning any kind of object using this AJAX call. I know I am doing something wrong, but I have no idea where. I hope someone can help me I am looking to return an element in the object "zip". I would like to have any response really, but I can not get anything back.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var result = $('#resultDiv')
$.ajax({
url: 'https://us-street.api.smartystreets.com/street-address',
method: 'get',
data: {
auth-id='your-auth-id',
auth-token='your-auth-token',
street=$('#street'),
city=$('#city'),
state=$('#state')
},
dataType: 'json',
success: function(data) {
if (data = null)
{
result.html('You failed');
}
else {
result.html('Match:' + data.components[0].zipcode)
}
}
});
});
});
</script>
<title>SSTest</title>
</head>
<body>
<div class="container">
<h1 style="text-align:center"> Welcome to Address Check </h1>
<form action="#" method="post">
<div class="form-group">
<label for="street">Street</label>
<input type="text" id="street" class="form-control" name="street">
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" id="city" class="form-control" name="city">
</div>
<div class="form-group">
<label for="state">State</label>
<input type="text" id="state" class="form-control" name="state">
</div>
<button type="submit" id="submit" class="btn btn-default">Submit</button>
<br/>
<br/>
<div id="resultDiv"></div>
</body>
</html>
As you are using a GET call, you can test this in the browser first AND make sure you are getting a response before you start wrapping it in a JQuery call.
https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=SOMETHING&state=SOMETHING&city=SOMETHING
If you get a non-result, then consult the API to see if you are passing the correct parameters.
Using the DOCS, this call returns data for your API Keys -
https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=1600+amphitheatre+pkwy&city=mountain+view&state=CA&candidates=10
This JQuery Get HTML example gets a response -
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("https://us-street.api.smartystreets.com/street-address?auth-id=[your-auth-id]&auth-token=[your-auth-token]&street=1600+amphitheatre+pkwy&city=mountain+view&state=CA&candidates=10", function(data, status){
alert("zipcode: " + JSON.stringify(data));
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
You should be able to build from that as you refine your JQuery understanding to get exactly what you need.
I was able to find a handful of errors with your code and fixed them here in this JSFiddle. Here are the list of errors you had.
Don't include your auth-id, auth-token in public code. You're giving away your address lookups by doing this. You should go remove these from your account and generate new ones.
In your original success function you didn't do a compare. You should use == here. Actually, the API will never send back null for data on success so you don't even need this here anymore. Use the error function instead.
The data object passed in the ajax call is done incorrectly. You should not be using =, instead use :.
In the data object you should call .val() after the jQuery selectors to get the values entered into those fields.
data.components[0].zipcode should be data[0].components.zipcode. The api will return back a data array of objects. components is not an array.
The auth-id and token should only be used when used from server side.
It is clearly mentioned not to expose the auth-id and auth-token in the documentation.
I used the FETCH API from Javascript and the code looks like this:
var key = '' //your embedded key here
var street = encodeURIComponent('1600 amphitheatre pkwy');
var city = encodeURIComponent('mountain view');
var state = 'CA';
var url = 'https://us-street.api.smartystreets.com/street-address?street=' + street + '&city=' + city + '&state=' + state + '&key=' + key;
const response = await fetch(url)
const responseData = await response.json()

How can i get response coming from web server

i have a form, i am asking customer to enter few details,
<form id="redirectForm" accept-charset="UTF-8" method="post" action="https://test.test.com//api/v1/order/create" >
customerName: <input type="text" name="customerName" value=<%=customerName %> />
customerEmail: <input type="text" name="customerEmail" value=<%=customerEmail %> /><br><br>
customerPhone: <input type="text" name="customerPhone" value=<%=customerPhone %> /><br><br>
signature:<input type="text" name="signature" value=<%=signature %> />
On submit page redirect according to action of form and display a JSON type response(status + payment link).
response is like:
{"status":"OK","paymentLink":"https:\/\/test.test.com\/billpay\/order\/3ackwtoyn7oks4416fomn"}
Help me out with this
i am working in jsp.
thank you in advance.
Since this look like a simple Webservice answer (not a full HTML page), I would use Ajax to send the form and manage the response.
With JQuery, this is easy using $.ajax
$.ajax({
url: //the URL
data: //the form value
method: //GET/POST
success: function(response){
//decode the JSON response...
var url = $.parseJSON(response).paymentLink;
//then redirect / not sure since this could be cross-domain...
window.loacation = url;
},
error: function(error){
...
}
})
The only think is that the form should not be send with a submit input, you need to link a button to a function doing this Ajax call.
This can be done without JQuery but I can write this from memory ;)
If you can edit the JSP creating the response, you could generate an HTML to return the value directly.
<html>
<head>
<script>
window.location.href = '${paymentLink}';
</script>
</head>
<body>
Redirection ...
<br>If nothing happend, you can <a href='${paymentLink}'>click here</a> to be redirected.
</body>
</html>
Where ${paymentLink} is a EL that will print the value of this variable (well the name it has on the server) to complete the script with the URL.
Once it is received by the client, it will be executed.
Of course, this will not be cross-domain on every browser. If this is not, you will need to provide the link to the user with <a href='${paymentLink}'>Redirection</a> itsefl.
Try this...
while submitting the form write one JS function and get the URL value.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function check(){
//here you have to get value using element name or id (val1,val2,val3)
$.ajax({
type:'GET',
data: {customerName: val1, customerEmail: val2,customerPhone: val3},
url:'https://test.test.com/billpay/order/3ackwtoyn7oks4416fomn',// Replace with Your Exact URL
success: function(response){
alert(response);
var json = JSON.parse(response);
var values = json.values;
for(var i in values)
{
var New_redirect = values[i].address;
alert(values[i].address);
}
window.loacation=New_redirect;
}
});
})
}
</script>
</head>
i think you are looking for response message and redirecting to somewhere
if so you can use the following code
if(condition)
{
response.sendRedirect("urpage.jsp");
}
or
if(condition)
{
request.getRequestDispacher("page.jsp");//enter the name of page you want to redirect inside ""
}

How to send JSON object/string (as 'POST') to a webservice using $resource in angularjs

I'm an absolute newbie in angularjs and don't have any idea about web services either.
My requirement is something like this:
I'll have a basic login page (to be designed using html and angularjs) which is going to ask for my credentials (Username and Password). On providing a set of credentials and clicking on the "Submit" button, my code needs to process the form data and pass the information on to a webservice. I just have the url of the webservice with me and nothing else.
Thus my principal objective would be to send across the username and password to the webservice (preferably as a JSON object) and check whether its working properly or not. So far, I've successfully managed to:
1> Hit the webservice (I've used $resource for doing the same.)
2> Store the username and password as a JSON object.
Now I need to accomplish two things:
1> send this data as "POST" and most importantly, 2> send this JSON data(as an object or string) to the webservice.
I'm absolutely clueless...Please help me out by modifying my code.
Thanks in advance. Here's my JS file:
var app = angular.module('angularjs-starter', ['ngResource']);
app.controller('MainCtrl', function ($scope,$http,$resource) {
$http.defaults.useXDomain = true;
$scope.checkUsername = function(){
var USERNAME = $scope.inputUsername;
var PASSWORD = $scope.inputPassword;
var f = JSON.stringify({USERNAME: USERNAME, PASSWORD: PASSWORD });
var result= JSON.parse(f);
var Something = $resource("/some url/:id", {id: "#id"},
{
post:{
method:"POST",
isArray:false
},
});
$scope.something = Something.get({id:1});
$scope.alertMessage = "Web service has been successfully hit!";
};
});
And here's my HTML file:
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Authentication</title>
<script src="C:\Users\Rup\Desktop\POC2\js\angular.js"></script>
<script src="C:\Users\Rup\Desktop\POC2\js\angular-resource.js"></script>
<script src="C:\Users\Rup\Desktop\POC2\experiment_2.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body ng-controller="MainCtrl">
<h1>Hello</h1>
<form name="form1" class="form-horizontal">
<label class="control-label" for="inputUsername">Username</label> <input
type="text" id="inputUsername" placeholder="Username"
ng-model="inputUsername"> <br /> <label
class="control-label" for="inputPassword">Password</label> <input
type="password" id="inputPassword" placeholder="Password"
ng-model="inputPassword"> <br /> <span class="help-block">{{alertMessage}}</span>
<br />
<!--<a class="btn">Sign in</a>-->
<button ng-click="checkUsername()">Submit</button>
</form>
</body>
</html>
The good news is that this should be fairly straight forward. You have the right idea, you just need to extend the resource object as you have done with "post" method, and when you call it - pass in your JSON object. Angular will then append the passed in JSON object as post parameters automatically. It's a good idea (I've read), to create this User resource as a service/factory so that you can inject it into your controllers to abstract the calls to the server. As an example - something I have done would be to create the service like so (with a dependency on the angular $resource):
var myApp = angualar.module('myApp', []);
myApp.factory('UserService', ["$resource",
function UserService($resource) {
var UserService = $resource('/rest/user', {}, {
search: {
method: 'POST',
url: window.location.origin +'/yourServer/rest/search' //custom url of your service to be called
}
});
return UserService;
}
])
Then in your controller, you inject the service to be used, and create a method that then calls your shiny new service:
myApp.controller("myAppController", ["$scope", "UserService",
function myAppCtrl($scope, UserService) {
$scope.search = function () {
var params = {
param1: "searchValue1",
param2: "searchValue2"
}
var response = UserService.search(params);
response.$promise.then(
function success() {
//celebrate!
},
function fail(err) {
//comiserate
}
);
}
}
The response object from the call to the service method is a promise, which you attach your success or fail functions to be called when the call successfully returns or fails.