calling a REST service from jquery - java

I have created a REST service at "/post/search/{id}" and when I call this URL from my jquery code sometimes it gets called sometimes not. What is the exact problem in it. Is it regarding jquery or my code. My jquery code is as follows:
function functionname(clicked_id) {
$('#idForm').submit(
function(e) {
$.ajax({
type : 'POST',
url : "${pageContext.request.contextPath}/post/search/"+ clicked_id,success : function(data) {
}
});
});
}
My button code is :
<input type="submit" value="Express Intrest" id="abc" onclick=functionname(this.id) />

try like this.
function yourFunc() {
$.ajax({
type : 'POST',
url : 'yourcontroller/action',
contentType : "application/json; charset=utf-8",
dataType : 'json',
data : param,
async : false,
cache: false,
success : function(dataList) {
//alert("dataList ---> "+dataList);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
//alert(XMLHttpRequest + " - " + errorThrown);
}
});
}
pass parameter values in param like this :-
var param;
param={param1:"val",param2:"val", param3:"val"};

change your button type from submit to button.
Because when you click on button your page start submitting.so the ajax function is sometime completed not completed before page.
<input type="button" value="Express Intrest" id="abc" onclick=functionname(this.id) />

Related

Java Ajax request parameters have null value

I'm trying to make a simple ajax request using Java (JSP + Servlet) and Ajax (jQuery). The Ajax request is working as expected, and the servlet code is reached.
The problem is that I can't get the values of the parameters sent by the request. I get null values.
This is the code in the servlet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
String perfilId = request.getParameter("perfilId"); //Null value
String perfilNombre = request.getParameter("perfilNombre"); //Null value
try (PrintWriter out = response.getWriter()) {
Gson gson = new Gson();
JsonObject obj = new JsonObject();
obj.addProperty("mensaje", "AlgĂșn mensaje. Id: " + perfilId + ", Nombre: " + perfilNombre);
out.print(gson.toJson(obj));
out.flush();
}
}
Ajax request inside a JSP:
$.ajax({
type: "POST",
url: 'srvl_def',
cache: false,
contentType: "application/json;",
dataType: "json",
data: {
perfilId: $('#perfilId').val(),
perfilNombre: $('#perfilNombre').val()
},
success: function (data) {
alert(data.mensaje);
}
});
The request data looks like this:
perfilId=1&perfilNombre=nuevo
Perhaps I'm missing something?
EDIT
This is the HTML
<input type="text" id="perfilId" />
<input type="text" id="perfilNombre" />
<button type="button" id="btnGuardar">Enviar</button>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$('#btnGuardar').click(function (){
//ajax call
});
</script>
Following this answer, #ShaunakD referenced this in a comment (see question), I was able to obtain the values sent by the ajax call.
The call looks like this:
var perfilId = $('#perfilId').val();
var perfilNombre = $('#perfilNombre').val();
$.ajax({
type: "POST",
url: 'srvl_def',
cache: false,
contentType: "application/x-www-form-urlencoded; charset=UTF-8;",
dataType: "json",
data: {
perfilId: perfilId,
perfilNombre: perfilNombre
},
success: function (data) {
alert(data.mensaje);
}
});
if your ajax call is inside some function try this :
var perfilId = $('#perfilId').val();
var perfilNombre = $('#perfilNombre').val();
$.ajax({
type: "POST",
url: 'srvl_def',
cache: false,
contentType: "application/json;",
dataType: "json",
data: {
perfilId: perfilId ,
perfilNombre: perfilNombre
},
success: function (data) {
alert(data.mensaje);
}
});

Need to get the response and to have change in ajax jquery GUI

I have the restful webservices call from the Jquery ajax and getting the response in json object.
Jquery HTML:
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
},
error: function (error, data) {
console.log(error);
}
});
}
});
And writing the response object for the restful webservices in java
#POST
#Path("api/{subsystem}")
#Produces("application/json")
public Response changeStatus(#PathParam("subsystem") String subsystem,
/*#FormParam("result")*/ String result) {
}
I got the response below and which is correct
changeStatus:88 - Reponse OutboundJaxrsResponse{status=200, reason=OK, hasEntity=true, closed=false, buffered=false}
Depending upon the reponse need to update the status whether the value is on/off in the label tag.
str = ' Status : ' + '' + onoffStat + '';
How can I achieve this in ajax and want to have the refreshing the div tag for every 2 seconds.
Please help me.
You will have to use Javascript polling. Try out something like this:
function ajaxPoll(){
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
tag.str = 'Status : ' + '' + ResData.status + '';
},
error: function (error, data) {
console.log(error);
}
});
}
});
}
setInterval(ajaxPoll, 2000);
Hope you sort it out :)

Handling JsonResponse in clientSide view technology of SpringMVC

I am trying to implement the below scenario in Spring MVC.But I am facing issues and not able to decide about the right Approach.
I am Using jsonRequest/jsonResone(Restful Webservices)
1.I have a SignUP.jsp Form which contains few field which need to be submitted to controller.
<form method="POST" onsubmit="javascript:signupObj.signup()">
<table>
<tr>
<td>Username : </td>
<td><input id="username"/></td>
</tr>
<tr>
<td>Password :</td>
<td><input id="password"/></td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
2.onSubmit of form it will invoke signup javascript function mentioned below
var signupObj = {
showSignup : function() {
//There are Two Ways to Declare Function The Other Way is function showSignup().Checkout the reasons
$.ajax({
type: "GET",
url: "showSignup",
success: function(response) {
$("#signupView").html( response );
}
});
},
signup : function() {
alert("In Signup function");
var input = '{';
input += '"username":"'+$('#username').val()+'",';
input += '"password":"'+$('#password').val()+'"';
input += '}';
alert(input);
$.ajax({
type: "POST",
url : "signup",
contentType: "application/json; charset=utf-8",
data: input,
dataFilter: function (response) {
return response;
},
// crossDomain: true,
async:false,
success: (function(data) {
alert("In ajax Sucess");
alert(data.profileID);
signupObj.redirectview("success",data);
}),
error : function(data,textStatus,error){
alert("In ajax Failure");
alert(error);
signupObj.redirectview("failure",data);
},
dataType: "json"
});
alert("ajax finished");
},
redirectview : function(message,data) {
alert("inside redirect view");
if(message == "success"){
url = "success";
}
else{
url = "error";
}
$.ajax({
type: "POST",
url : "success",
contentType: "application/json; charset=utf-8",
data: data,
async:false,
dataType: "json",
dataFilter: function (response) {
return response;
},
// crossDomain: true,
success: (function(data) {
alert("data");
}),
error : function(data,textStatus,error){
alert("In ajax Failure redirect");
alert(error);
},
});
}
};
3.The Above javascript function does the ajax call to the controller(input is jsonRequest)
#RequestMapping(value="/signup",method=RequestMethod.POST)
#ResponseBody
public ProfileDTO signup(#RequestBody LoginDTO loginDTO) {
ProfileDTO profileDto = new ProfileDTO();
//In case no errors in backend logic
profileDto.setError(null);
profileDto.setProfileID("profileID");
profileDto.setProfileName("profileName");
System.out.println("Submitting SignUP Form Will Return ProfileID");
return profileDto;
}
//Below method is for success view
#RequestMapping(value="/success",method=RequestMethod.POST)
#ResponseBody
public String checkSignup(#RequestBody ProfileDTO profileDto,HttpServletRequest httprequest,HttpServletResponse httpResponse
) {
//model.addAttribute(loginDTO);
System.out.println("In loginSuccess");
return "loginSucess";
}
4.The Controller gives the JSON Response of profileDTO. Now based on the profileDTO.getErrors I have to call either loginSuccess.jsp or loginFailure.jsp
Now My Question is:
1) How I can use jsonResponse in ajax call to redirect to loginSuccess.jsp or loginFailure.jsp and how will pass my profileDTO data to the loginSuccess view.
2.)Please Suggest me the Best Practice Which should be Followed.
1.) First of all you can reduce your code in javascript like below, Directly serialize the form object.
var signupObj = {
signup : function() {
alert("In Signup function");
$.ajax({
type: "POST",
url : "signup",
data: $('#myForm').serialize(),// add "myForm" as the form id
async:false,
success: (function(data) {
alert("data"+data);
redirectView("success",data);
})
error : function(data, textStatus, errorThrown) {
alert(error_occured);
redirectView("error",data);
}
});
}
};
<script
function redirectView(message,data){
var url = "";
if(message == "success"){
url = "/success";
}else{
url = "/error";
}
$.ajax({
type: "POST",
url : url,
data: data
async:false,
success: (function(data) {
alert("data"+data);
})
error : function(data, textStatus, errorThrown) {
alert(error_occured);
}
});
}
</script>
2.) Redirect the success or failure view from the controller itself.
3.) Pass my profileDTO data to the loginSuccess view.
Spring MVC, from version 3, allows you to return objects directly converted into JSON using the #ResponseBody annotation in a Controller as shown here
#RequestMapping(value="/signup",method=RequestMethod.POST)
#ResponseBody
public ProfileDTO signup(#ModelAttribute("LoginDTO") LoginDTO loginDTO,BindingResult bindingResult) {
ProfileDTO profileDto = new ProfileDTO();
//In case no errors in backend logic
profileDto.setError(null);
profileDto.setProfileID("profileID");
profileDto.setProfileName("profileName");
System.out.println("Submitting SignUP Form Will Return ProfileID");
return profileDto;
}
If Forward from controller
With a prefix of forward, Spring will get a RequestDispatcher for the specified path and forward to it. Part of that process will include taking the Model from the ModelAndView created for that request handling cycle and putting all its attributes into the HttpServletRequest attributes.
The Servlet container will take the RequestDispatcher#forward(..) and again use your DispatcherServlet to handle it. Your DispatcherServlet will create a new ModelAndView with a new Model for this handling cycle. Therefore this Model doesn't contain any of the attributes from before but the HttpServletRequest attributes do.
In your case, this
modelMap.put("key", "value");
will end up being in
HttpServletRequest request = ...;
request.getAttribute("key");

Getting JavaScript JSON string to populate DataTable

I have a java function that gets a JSON string of data from a Servlet in Java. I am trying to use that data to populate a datatable (http://www.datatables.net/examples/data_sources/ajax.html)
This is the way that the DataTables website instructs users to populate datatables:
$(document).ready(function() {
$('#example').dataTable( {
"ajax": '../ajax/data/arrays.txt'
} );
} );
And this is the javascript method that calls the doPost method in my servlet to generate and return the JSON:
<script>
$(document).ready(function() { // When the HTML DOM is ready loading, then execute the following function...
//$('#somebutton').click(function() { // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
var bodyContent = $.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
async : false,
success : function() {
console.log("ok");
alert("ok");
}
}).responseText;
console.log(bodyContent);
});
</script>
How can I get the JSON string in var bodyContent to populate the datatable?
First off, you're not really doing AJAX; when you do:
var bodyContent = $.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
async : false,
success : function() {
console.log("ok");
alert("ok");
}).responseText;
You set async: false ... but AJAX stands for Asynchonous Javascript and XML. With an AJAX approach the following happens:
You start the request by doing $.ajax
The server takes however long to respond; the user's browser is not locked up during this time
When the server responds the success callback you defined gets called
With your approach
You start the request by doing $.ajax
The user's browser is locked up while waiting for a response
When the server responds your code (after the $.ajax call) is invoked.
To make your code actual AJAX do this instead:
var bodyContent = $.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
success : function(responseText) {
bodyContent = responseText
}
});
Of course, once the response comes back you also need to build your Data Table, so what you really want is:
success : function(responseText) {
$('#example').dataTable( {
"data": responseText
});
}
(Or something to that effect; I forget DataTable's exact syntax.)
Refer to jQuery.ajax docs. The data returned from server in first argument of success callback. Also note that all manipulations with this data whould be inside this callback. I guess you should additionally check status argument:
$(document).ready(function() {
var bodyContent = null;
$.ajax({
url : "DAOserv",
global : false,
type : "POST",
data : "name=value",
dataType : "json",
success : function(data, status) {
console.log(data);
$('#example').dataTable( {
"data": $.parseJSON(data),
"columns": [
{ "title": "Engine" },
{ "title": "Browser" },
{ "title": "Platform" },
]
});
});
});
});
UPDATE To populate data server should respond with JSON encoded array of data and you should parse it and pass to dataTable as it noted here.

value is not passed to controller

i have a problem with passing values to the controller(jave) from javascript file after serialising the entries. when i run in debug mode its passing values to the controller but if its run straight away then its not passed. i first serilzed the values entered in the form and then post to the controller. any ideas please... the code is as follows function
submitSearch() {
var searchParams = $("#search-filters, #keyword-desktop-filters, #keyword-mobile-filters").serialize();
alert(searchParams);
$.ajax({
url: 'search?' + searchParams,
type: 'POST',
success: function (msg) {
alert("hai");
},
error: function (xhr) {
alert("kooyi");
}
});
}
Try to pass your search parameters like data parameter in your .ajax function settings object. Here the example:
$.ajax({
url: 'search' ,
type: 'POST',
data: $("#search-filters, #keyword-desktop-filters, #keyword-mobile-filters").serialize(),
success: function (msg) {
alert("hai");
},
error: function (xhr) {
alert("kooyi");
}
});
And here is .ajax method' API: http://api.jquery.com/jQuery.ajax/

Categories

Resources