value is not passed to controller - java

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/

Related

RequestParam annotation doesn't work with POST

I have the following controller:
#RequestMapping(value = { "/member/uploadExternalImage",
"/member/uploadExternalImage" }, method = RequestMethod.POST)
public String handleFileUpload(#RequestParam("url") String url,
Principal principal) throws IOException {
File file = restTemplate.getForObject("url", File.class);
file.toString();
return null;
}
And I have the following ajax:
$.ajax({
url: 'uploadExternalImage', //Server script to process data
type: 'POST',
success: function () {
},
complete:function(){
$.fancybox.hideLoading();
},
// Form data
data: {url: files[0].link},
cache: false,
contentType: false,
processData: false
});
in spring log I see that
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'url' is not present
if I change ajax method with GET:
$.ajax({
url: 'uploadExternalImage?url=123', //Server script to process data
type: 'POST',
success: function () {
},
complete:function(){
$.fancybox.hideLoading();
},
error: function (data) {
},
cache: false,
contentType: false,
processData: false
});
it works fine
How does to configure spring correctly?
Http POST is capable of being used for request parameters on request body. But you are trying to use it on a different way.
Try this:
$.ajax({
type: 'POST',
url: "uploadExternalImage?url=BLABLA",
data: text,
success: function (data) {
//
}
});
If you want it on request body then use #RequestBody

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 :)

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.

Using a Map as the RequestBody for a Spring AJAX request (using ExtJS)

I am trying to make an AJAX call from ExtJS to a Spring 3.1.3 backend, using PUT and with a Map as a request parameter. I can successfully make a similar call using a List param and passing a JavaScript array of strings, but cannot get a Map to work using a JavaScript object.
In other words, this works:
#RequestMapping(value="stringTest", method=RequestMethod.PUT)
public #ResponseBody String stringTest(#RequestBody List<String> list) {
//do stuff
return "OK";
}
Ext.Ajax.request({
url: "stringTest",
method: 'PUT',
jsonData: ['one','two'],
success: function() { console.log('ok'); },
failure: function(){ console.log('fail'); }
});
However, this does not work:
#RequestMapping(value="mapTest", method=RequestMethod.PUT)
public #ResponseBody String mapTest(#RequestBody Map<String,String> map) {
//do stuff
return "OK";
}
Ext.Ajax.request({
url: "mapTest",
method: 'PUT',
jsonData: {one: 'one', two: 'two'},
success: function() { console.log('ok'); },
failure: function(){ console.log('fail'); }
});
The request itself does not fail (no 400 error), but the map itself is empty when the mapTest method is instantiated.
One curious point I have discovered is that I am able to make this work using both jsonData and params (but not one or the other) as part of the Ext.Ajax.request, like this:
var data = {one: 'one', two: 'two'};
Ext.Ajax.request({
url: "mapTest",
method: 'PUT',
jsonData: data,
params: data,
success: function() { console.log('ok'); },
failure: function(){ console.log('fail'); }
});
However, I can't use this approach because I cannot have the extra parameters passed as part of the URL string, which is what this ends up doing.
So, the question is, how can I use a Map as my request param, using just jsonData for the request body?

calling a REST service from jquery

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) />

Categories

Resources