calling a Java method by AJAX - java

Actually I've been reading about this for a while but I couldn't understand it very well.
Here is a snippet of the Servlet "ProcessNurseApp" :
if (dbm.CheckExRegNumber(Candidate.getRegNumber()) == true) {
// Show him an alert and stop him from applying.
out.println("<script>\n"
+ " alert('You already Applied');\n"
+ "</script>");
out.println("<script>\n"
+ " window.history.go(-1);\n"
+ "</script>");
}
So when the form named "ApplicationForm" in the "Nurses.jsp" get submitted it goes to that method in servlet after some Javascript validation.
My issue is that I want to call that method
if (dbm.CheckExRegNumber(Candidate.getRegNumber()) == true)
in the JSP page without getting to servlet so I can update values without refreshing the page. I've been reading that using ajax with jQuery would be the best way to do that, so can anyone help me of calling the above if statement from jQuery by AJAX.

Try an ajax call to the servlet(not possible without calling servlet) to check whether the function returns true or false then return a flag according to the value(true or false). On that basis you can show an alert or anything else.
For ajax call, you can use:
$.post( "ajax/Servlet_Url", function( data ) { if(data==true) alert("You already Applied"); else window.history.go(-1);});
Refer to following Link for more details about jQuery post request.
https://api.jquery.com/jquery.post/

jQuery(document).ready(function($) {
$("#searchUserId").attr("placeholder", "Max 15 Chars");
$("#searchUserName").attr("placeholder", "Max 100 Chars");
$.ajax({
url:"../../jsp/user/userMaster.do",
data: { drpType : 'userType',lookType : "1" },
success: function (responseJson) {
var myvalue = document.getElementById("userTypeKey");
for(var val in responseJson)
{
valueType = val;
textOptions = responseJson[val];
var option = document.createElement("option");
option.setAttribute("value",valueType);
option.text = textOptions;
myvalue.add(option);
if(valueType == myvalue.value)
{
option.selected = "selected";
}
}
}
});
});

Related

JSON.stringify() doesn't work on big html data

Angular.js
$scope.exportTable = function (param, isId) {
//var excelContents = JSON.stringify( $((isId) ? "#"+param:"."+param).html());
console.log(JSON.stringify($((isId) ? "#" + param : "." + param).html()));
$interval($scope.downloadExcel(JSON.stringify($((isId) ? "#" + param : "." + param).html())), 3000);
};
$scope.downloadExcel = function (excelContents) {
console.log("this should be displayed after 3 seconds");
$.ajax({
url: urls.BASE_API + "user/setExcelContents",
data: {excelContents: excelContents},
type: 'POST',
dataType: 'json',
complete: function (data) {
if (data.responseText == "1") {
window.location.href = urls.BASE_API + "user/exportExcel";
}
}
});
};
Here I'm trying to send 1600 table rows to a controller method in Java, which then I will catch the param with #RequestParam('excelContents')
This throws error on Request parameter is not present
Now, If i send like 20-50 table rows, this works fine without any errors.
I was thinking that JSON.stringify() can't complete its task BEFORE I send it as the parameter, so thats why I added the $interval, but $interval doesn't work. it doesn't pause for 3 seconds (3000 milliseconds) when I pass the argument. The method runs as soon as I call it, without any pausing.

struts2 ajax call response always shows null

I am trying to call the struts2 action class from my jsp using ajax. I can hit the action class and able to pass the parameters to action class. But the response that comes from action class to my ajax request is always null
All setters and getters are set correctly and they are working fine when I see in debug sysouts
Action Class
#Override
#Action(value = "/search",
results = { #Result(name = "success", type="json")})
public String execute() throws ParseException
{
this.setName(this.term+": "+this.pos);
System.out.println("Name: "+Name);
JSONObject json = (JSONObject)new JSONParser().parse(Name);
return ActionSupport.SUCCESS;
}
jsp
function Search()
{
var term = document.getElementById("term").value;
var pos = document.getElementById("pos").value;
var itr = document.getElementById("itr").value;
var pri = document.getElementById("pri").value;
var atb = document.getElementById("atb").value;
var jsonData = {};
jsonData.term = term;
jsonData.pos = pos;
jsonData.itr = itr;
jsonData.pri = pri;
jsonData.atb = atb;
$.ajax({
type: "POST",
url: "search",
dataType: "json",
data: jsonData,
success: function(response){
console.log(""+response);
alert('Name: '+response.Name);
//alert('Length: '+data[0].length);
/* $.each(data[0],function(index, value){
alert("value " +value);
});*/
},
error: function(response){
alert(response);
alert(response.length);
$.each(response,function(index, value){
alert("value " + value);
});
}
});
}
I can see the response always as null. I am not sure what is going wrong, but seems the coding part is correct. Am I doing some mistake in ajax call?
As clearly explained in this answer, you need to use the JSON plugin, that will serialize the entire action (or a single root object when needed). You don't need then to do the parsing yourself, just evaluate the name variable.
To send JSON from JSP to action instead you need to use the JSON Interceptor in your stack.
Ensure you have getters and setters for everything.
Your Name variable should be name, both in Java and in Javascript. Only the accessors / mutators should use the capitalized N (getName, setName).
If the error persists, check carefully console and logfiles for errors, with devMode set to true.
Since this comment has gone too far, I've turned it into an answer :)

java spring boot pass array of strings as parameters inside json for ajax call

In my application I need to pass an array of parameters form client side to server side. I tried the following code but its not working.I need to get data from checkbox list and pass it to server side.
My code for the client side
$(".add").click(function(){
monitoring.length=0;
nonMonitoring.length=0;
$('.modal-body input:checked').each(function() {
monitoring.push($(this).val());
});
$('.addkeywords input:checked').each(function() {
nonMonitoring.push($(this).val());
});
// alert(monitoring[2]+ " " + nonMonitoring[2]);
var monitoringLength=monitoring.length;
var nonMonitoringLength=nonMonitoring.length;
$.ajax({
type : "GET",
url : '/rest/my/rest/mysql/controller',
data : {
monitoringLength: monitoringLength,
nonMonitoringLength: nonMonitoringLength,
monitoring : monitoring,
nonMonitoring: nonMonitoring,
},
success : function(data) {
// var keywordsList=data
//console.log(keywordsList);
// htm = "" ;
if(data=='success'){
// loadChannels();
location.reload();
}else{
alert("failed to upload");
}
}
});
})
My code for the server side.
#RequestMapping("/rest/my/rest/mysql/controller")
public void monitorKeywords(#RequestParam(value="monitoringLength",required=true)int monitoringLength,#RequestParam(value="nonMonitoringLength",required=true)int nonMonitoringLength,#RequestParam(value="monitoring",required=true)List<String> monitoring,#RequestParam(value="nonMonitoring",required=true)List<String> nonMonitoring){
System.out.println("MonitoringLength =>" +monitoringLength);
System.out.println("NonMonitoringLength=>" +nonMonitoringLength);
System.out.println("Monitoring=>" +monitoring);
System.out.println("Monitoring=>" +nonMonitoring);
Somehow this is not working.What is the error in this? Please help
In Request parameter change List to array
i.e.
#RequestParam(value="monitoring",required=true) String[] monitoring, #RequestParam(value="nonMonitoring",required=true) String[] nonMonitoring

How to save the response data return by Facebook in Java class using Spring MVC

I am trying to save the user data which is return by the Facebook response.
I am using Facebook Javascript.Response is in JSon format and I want to parse it first and then save it in to my database using java.
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
/* var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
console.log("User id is" + uid);
console.log(accessToken); */
document.getElementById('accesstoken').value=response.authResponse.accessToken;
console.log(response.authResponse.accessToken);
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxxxxxxx',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.2' // use version 2.2
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
// window.location="http://localhost:8080/SpringMvcHibernateJavaBased/list";
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
console.log(response);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
document.getElementById('usernamefb').value=response.name;
document.getElementById('userId').value=response.id;
document.getElementById('emailfb').value=response.email;
});
}
function checkLogoutState(){
FB.logout(function(response) {
FB.Auth.setAuthResponse(null, 'unknown');
});
};
function checkData()
{
return $.ajax({
})
}
</script>
I am using Spring MVC approach fully JAVA based not using any xml files.
I have searched lot but didn't get any solution
In "if (response.status === 'connected') {}" block you need to call another API of Facebook to fetch the user's details by passing user id and token and after receiving the data you can call your own controller through Ajax and save into DB if required.
Another solution can be, you may use "http://projects.spring.io/spring-social/" on server side itself.
Krish

How to show value from database to jsp without refreshing the page using ajax

I am an Ajax fresher
Ajax
function ajaxFunction() {
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","Namelist",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
jsp
<form name="fname" action="Namellist" method="post">
Select Category :
<select name="txtname" id="txtname">
<option value="Hindu">Hindu</option>
<option value="Muslim">Muslim</option>
<option value="Christian">Christian</option>
</select>
<input type="button" value="Show" id="sh" onclick="ajaxFunction();">
<div id="message">here i want to display name</div><div id="message1">here i want to display meaning</div>
</form>
servlet
String ct=null;
ct=request.getParameter("txtname");
Connection con=null;
ResultSet rs=null;
Statement st=null;
try{
con=Dbconnection.getConnection();
PreparedStatement ps=con.prepareStatement("select name meaning from (select * from namelist order by dbms_random.value)where rownum<=20 and category='+ct+'" );
rs=ps.executeQuery();
out.println("name" + rs);
**Here I have confusion,**
}
catch(Exception e)
{
System.out.println(e);
}
How can i diaplay servlet value to jsp.
Please help me? or please provide some good tutorial links.
You have to make below changes :-
In Servlet :-
Set the response content type as:- response.setContentType("text/xml"); in top section of the servlet. By setting this we can send the response in XML format and while retrieving it on JSP we will get it based on tag name of the XML.
Do whatever operation you want in servlet...
Save the value for ex-
String uname=";
uname="hello"; //some operation
//create one XML string
String sendThis="<?xml version='1.0'?>"
+"<Maintag>"
+"<Subtag>"
+"<unameVal>"+uname+"</unameVal>"
+"</Subtag>"
+"</Maintag>"
out.print(sendThis);
Now we'll go to JSP page where we've to display data.
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
if(xmlhttp) {
xmlhttp.open("GET","NameList",true); //NameList will be the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
getVal();
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
function getVal()
{
var xmlResp=xmlhttp.responseText;
try{
if(xmlResp.search("Maintag")>0 )
{
var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Subtag");
var xx=x[0].getElementsByTagName("unameVal");
var recievedUname=xx[0].firstChild.nodeValue;
document.getElementById("message").innerText=recievedUname;//here
}
}catch(err2){
alert("Error in getting data"+err2);
}
}
And here you are done. :)
1.In servlet code
PrintWriter output = response.getWriter();
String result = "value";
writer.write(result);
writer.close()
2. Why you don't use jquery ?
You can replace your code on -
$.post('url', function(data) {
$('#message1').html(data);
});
query post example
Probably off the hook but might be useful, rather than putting up all the javascript for Ajax call use some javascript library preferably jQuery for making the Ajax call.
Any javascript library you use will help you make the code compact and concise and will also help you maintain cross browser compatibility.
If you planning to write all the XHTTP code yourself, you might end up spending a lot of time for fixing cross browser issues and your code will have a lots of hacks rather than the actual business logic.
Also, using library like jQuery will also achieve the same stuff with less number of lines of code.
Hope that helps.

Categories

Resources