Submitting Serialized JSON to a Servlet - json

I can successfully serialize the form and submit it to a text area in the form, but don't know how to send it to a Servlet that I have already created/defined:
// Prepare form for Serialize
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
// Send JSON Data to ResultSet
$(function() {
$('form').submit(function() {
//submitting to textarea "resultset"
//needs to submit to servlet "SftpConnTest" as defined in web.xml
//$('#ResultSet').text(JSON.stringify($('form').serializeObject()));
//?? HOW DO I SEND TO "SftpConnTest" SERVLET instead??
return false;
});
});

Use following to send form data via ajax to server:
$.post("path/to/servlet", $("#formId").serializeArray(), function (result) {
// do something
});
By the way:
serializeArray() will convert a form to an array, which could be used directly as the "data" param of a jquery ajax request, only element that has a name property in the form will be included into the data,for details please check jquery api, it's very clear there.

Assuming you are sending this to the servlet using an HTTP POST, you can use ajax:
$(function() {
$('form').submit(function(evt) {
evt.preventDefault(); // prevent the default form submit behavior
var data = $('form').serializeObject();
$.post(
'/',
data,
function(resData, status, req) {
$('#ResultSet').text(JSON.stringify(resData));
}
);
}
}
If the servlet is not mapped to be located at the root of the web app, replace 'SftpConnTest' in the $.post function with the relative path to the servlet. For example, if the servlet is mapped to /foo/bar/SftpConnTest, then you should have '/foo/bar/SftpConnTest' instead of 'SftpConnTest'.
See the jQuery docs for more information on the $.post function.

Related

Polymer data binding from Web API

I want to bind some data to a variable on command (by the press of a button) from a server. On the server I have a function that will return a JSON object (this has been tested, if I open the API link directly, I do get the proper JSON format). However, the variable stays undefined, no matter what I do. I have a button and a table (px-data-table is part of a framework and should be able to display JSON formatted data):
<button id="runPredictionButton">
<i>Button text</i>
</button>
<px-data-table
table-data$="{{data}}"
</px-data-table>
<div class="output"></div>
And I'm handling the button press and define the variables as follows:
<script>
Polymer({
is: 'custom-view',
properties: {
data: {
type: Object,
notify: true
}
},
ready: function() {
var self = this;
this.$.runPredictionButton.addEventListener('click', function() {
filerootdiv.querySelector('.output').innerHTML = 'Is here';
var xhr = new XMLHttpRequest();
this.data = xhr.open("GET", "API/predict") //as mentioned, API/predict returns a valid JSON
console.log("This data is:" + this.data);
this.data = xhr1.send("API/predict","_self")
console.log("This data is_:" + this.data);
});
}
});
</script>
For some reason, on the console this.data shows up as undefined both times I'm trying to print it. What am I missing? How to pass the JSON from the API call to the this.data variable?
xhr.send() doesn't return what you want.
You need to learn XmlHttpRequest first. Here is documentation. And some easy examples
Simply, you need to listen to onreadystatechange on your xml variable. There you will be able to get data from server.
Additionaly, why are you using addEventListener. You can simply set on-click.
<button id="runPredictionButton" on-click="getDataFromServer">
<i>Button text</i>
</button>
and then you can define javascript function which is called everytime user clicks on button.
getDataFromServer: function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "API/predict");
xhr.send("API/predict","_self");
xhr.onreadystatechange = function() {
// 4 = data returned
if(xhr.readyState == 4) {
// 200 = OK
if (this.xhttp.status == 200) {
// get data
this.data = xhr.responseText;
}
}
}.bind(this);
}

Login Service implementation in angularjs not working

This is my controller which is calling the login service
mod.controller("loginCtrl",function($scope,loginService,$http)
{
$scope.Userlogin = function()
{
var User = {
userid :$scope.uname,
pass:$scope.pass
};
var res = UserloginService(User);
console.log(res);
alert("login_succ");
}
});
And this is the login service code which takes the User variable and checks for username & password
mod.service("loginService",function($http,$q) {
UserloginService = function(User) {
var deffered = $q.defer();
$http({
method:'POST',
url:'http://localhost:8080/WebApplication4_1/login.htm',
data:User
}).then(function(data) {
deffered.resolve(data);
}).error(function(status) {
deffered.reject({
status:status
});
});
return deffered.promise;
// var response = $http({
//
// method:"post",
// url:"http://localhost:8080/WebApplication4_1/login.htm",
// data:JSON.stringify(User),
// dataType:"json"
// });
// return "Name";
}
});
I have created a rest api using springs which upon passing json return back the username and password in json like this
Console shows me this error for angular
You need to enable CORS for your application for guidance see this link
https://htet101.wordpress.com/2014/01/22/cors-with-angularjs-and-spring-rest/
I prefer to use Factory to do what you're trying to do, which would be something like this:
MyApp.factory('MyService', ["$http", function($http) {
var urlBase = "http://localhost:3000";
return {
getRecent: function(numberOfItems) {
return $http.get(urlBase+"/things/recent?limit="+numberOfItems);
},
getSomethingElse: function(url) {
return $http.get(urlBase+"/other/things")
},
search: function (searchTerms) {
return $http.get(urlBase+"/search?q="+searchTerms);
}
}
}]);
And then in your controller you can import MyService and then use it in this way:
MyService.getRecent(10).then(function(res) {
$scope.things = res.data;
});
This is a great way to handle it, because you're putting the .then in your controller and you are able to control the state of the UI during a loading state if you'd like, like this:
// initialize the loading var, set to false
$scope.loading = false;
// create a reuseable update function, and inside use a promise for the ajax call,
// which is running inside the `Factory`
$scope.updateList = function() {
$scope.loading = true;
MyService.getRecent(10).then(function(res) {
$scope.loading = false;
$scope.things = res.data;
});
};
$scope.updateList();
The error in the console shows two issues with your code:
CORS is not enabled in your api. To fix this you need to enable CORS using Access-Control-Allow-Origin header to your rest api.
Unhandled rejection error, as the way you are handling errors with '.error()' method is deprecated.
'Promise.error()' method is deprecated according to this and this commit in Angular js github repo.
Hence you need to change the way you are handling errors as shown below :
$http().then(successCallback, errorCallback);
function successCallback (res) {
return res;
}
function errorCallback (err) {
return err;
}
One more thing in your code which can be avoided is you have defined a new promise and resolving it using $q methods, which is not required. $http itself returns a promise by default, which you need not define again inside it to use it as a Promise. You can directly use $http.then().

Dynamic html page in thymeleaf + Spring based on selected option in drop down menu

I am developing a web application using the Spring framework and Thymeleaf.
I have created a drop down menu, but I want something else on the page to appear when a certain option in the drop down menu is selected. By selected I mean when the option in the menu is clicked on and nothing more. I do not mean complete form submission.
I have read through the docs but found no solution.
Any ideas?
Thanks
You ca use JS using th:inline like this, explanation is on comment
JS code
<script th:inline="javascript">
//Declare the URL of RequestMapping to use
//Do no change format
/*[+
var urlToload = [[#{/path/spring}]];
var anotherUrlToUse = [[#{/another/url?param=}]];
+]*/
//Handle you jquery event
$('body').on('click', '.dropdown-menu', function (e) {
var t = $(this);
//Sending your ajax request
$.ajax({
url: urlToload,
method: 'POST',
data: {
optionSelected: t.val()
}
})
/**
* Execute when your request is done
* #param {type} data : the page result of your Request *
*/
.done(function (data) {
$("#receiver").html(data);
})
//Execute on fail
.fail(function (xhr, ajaxOptions, thrownError) {
console.log("ERROR");
//Use anotherUrlToUse with GET METHOD to redirect
window.location.replace(anotherUrlToUse+404);
});
});
</script>
Controller code
#RequestMapping(value = "/path/spring", method = RequestMethod.POST)
public String controllerMethod(Model model, #RequestParam("optionSelected") String optionSelected) {
/**
* Do your job
* Your code
*/
return "page/result";
}

How to return Json Object from view to controller MVC4.

I have this script to extract form data and serialize to Json Object:
form = document.forms[0];
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function () {
form.submit(function () {
result.append(JSON.stringify(form.serializeObject()));
return false;
});
});
I want to put this on an html button and then send the object resulted in the controller.But how?
The action will be an JSONResult() ?
How do i can do all this? THX
Attach onclick event on button.
Use jquery ajax call to post json to action in controller
Return a action result as json object.
Do whatever you want on sucess event of jquery ajax call procedure.
For details ask google!

How to handle multiple submit buttons using mootools?

In prototype you can use the following code.
var form = control.form;
new Ajax.Updater('result', form.action,
{ method: 'post',
parameters: form.serialize({submit: control.name})
}
);
return false;
Is there something like this in mootools? Simple but elegant ?
Yes, there is Form.Request
i.e.
(function($){
new Form.Request($('formID'), $('responseID'), {
onSuccess : function() {
//form submitted correctly
}
});
})(document.id);
where $('formID') is your form, and $('responseID') is the element that will hold the response (i.e. a response message)