POST to a REST service using Ajax is failing - javascript

I am working with a javascript client that I am trying to use to communicate with a server. I have a Javascript function that is POSTing to a Spring Boot REST service. The service is a simple test service that doesn't do much...
#RequestMapping(method = RequestMethod.POST,value="/testservice")
#ResponseBody
public String testPostRequest(#RequestParam String someText)
{
System.out.println("Reached the counting service! Param value: " + someText);
if(someText != null)
{
...
perform some actions
...
}
return("Success");
}
The Javascript I am using to send POST requests to the server is below:
var sendWords = function(toSend) {
var data = { DataList : [toSend] };
var param = { someText: data };
$.post("http://localhost:8080/testservice",param,
function(status,ret) {
alert("We're back "+status);
});
};
The toSend parameter is just a string containing some text that will be posted to the service. Note that the port for the service was set to 8080 in the server's application.properties file.
When I call the Javascript function and post the string to the service, I get the following log message from the server:
2019-07-28 20:00:06.292 WARN 80844 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'someText' is not present]
I am doing something wrong, but cannot figure out what it is. I am sending an object that is tagged as the someText string, but it is not being recognized by the server for some reason.
Can someone tell me what I am missing? How do I get this to work?

var data = { DataList : [toSend] };
var param = { someText: data };
Here data is not string.
You may need to stringify it.
var param = { someText: JSON.stringify(data) };

You are missing the value in the #RequestParam(), such as #RequestParam(value="someText", required=true).
You could use #PathVariable too.
This could be helpful:
#RequestParam vs #PathVariable

Related

NodeJS GET request not working with AngularJS

I have this web app that is for sharing photos.
Now I have this route that is supposed to return the photos of all the users from the following array.
Route:
router.get('/getphotos',function(req, res){
var reqPhotos = [];
console.log( "\n" + req.body.username + "\n");
try{
for(x =0; x < req.body.following.length; x++){
reqPhotos.push({username: req.body.following[x].username});
}
}
catch(err){
console.log(err);
}
Photo.find({username: reqPhotos}).exec(function(err, allPhotos){
if(err){console.log(err);}
else{
res.json(allPhotos);
}
});
});
I have found out that the req.body.following was undefined. This is how I was calling it using angular:
$scope.getPhotos = function(){
if($scope.identification){
flng = angular.copy($scope.identification.following);
flng.push($scope.identification.username);
var data = {username: $scope.identification.username, token: $scope.identification.token, following: flng}
//IDENTIFICATION HAS ALL THE INFO.
$http.get('/users/getphotos', data).success(function(response){
$scope.photos = response;
});
}
}
Why does this happen and how to fix it?
Thanks!
Not sure about the server side, but I see two problems in the angular code. You cannot pass a body when doing an HTTP GET request. Try to pass any necessary data through the url.
Also, the actual data that is returned, will be in response.data. Do something like this:
var urlData = ""; //add any url data here, by converting 'data' into url params
$http.get('/users/getphotos/' + urlData).then(function(response){
$scope.photos = response.data;
});
For constructing the urlData, have a look at this question.
Of course, you will have to adjust the server so it reads the data from the url, rather than from the body.
I don't know what the Content-Type in request request header, is that application/json or application/x-www-form-urlencoded or other. Every content type have to be treated differently. If you use expressjs, try using multer to handle request with multipart-form content type, I usually use it in my application.
$http doesn't take a 2nd parameter for a data object in GET method. However, $http does accept a data object as the 2nd parameter in POST method.
You'll need pass it as the params property of the config object and access it in your req.query in node:
$http.get('enter/your/url/', { params: data})

Succesfull $.Ajax and $.Post calls always return failure from C#

I need a cross domain web api method to return valid jsonp to some javascript from C#. I can't seem to make this magic happen. I've looked around the web and can't find a start to end example that fits my needs and works... Fiddler shows that I'm returning valid json data but when I hit a breakpoint in F12 dev tools or firebug the result is a failure message.
Here is what I've currently got:
C#
/// <summary>
/// POST: /Instance/RefreshItem
/// </summary>
/// <param name="instanceId"></param>
/// <returns>Json</returns>
[HttpPost]
public System.Web.Mvc.JsonResult RefreshItem(int instanceId, Guid customerId)
{
try
{
var clientConnection = Manager.ValidateInstance(customerId, instanceId);
clientConnection.RefreshItem();
var result = new MethodResult()
{
Success = true,
Value = instanceId,
Message = "Item successfully refreshed."
};
return new System.Web.Mvc.JsonResult() { Data = result };
}
catch (Exception ex)
{
Manager.LogException(_logger, ex, customerId, instanceId);
var result = new MethodResult()
{
Success = false,
Value = instanceId,
Message = ex.GetBaseException().Message
};
return new System.Web.Mvc.JsonResult() { Data = result };
}
}
JS
Example.RefreshItem = function ()
{
Example.SDK.JQuery.getSettings(
function (settings, userId, userLocaleId)
{
alert("Attempting to refresh item for instance " + settings.ConnectionId + "\r\nThis may take awhile.");
var url = settings.SystemUrl + "/Api/WebApiServices/ExampleAdmin/RefreshItem?customerId=" + settings.CustomerId + "&instanceId=" + settings.ConnectionId;
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'RefreshItemCallback',
success: RefreshItemCallback
})
},
Example.SDK.JQuery.defaultErrorCallback
);
}
function RefreshItemCallback(data)
{
alert(data.d.Message);
}
I've also tried $.Post().Always() with the same results.
What am I doing wrong???
I think your problem is that you're instantiating a JsonResult instead of using the Json method.
Presumably the C# method you have is in a controller, so instead of
return new System.Web.Mvc.JsonResult() { Data = result };
do:
return Json(result);
This method probably sets some of the other properties of the JsonResult that, when not set, will not be properly received by the client.
See how Microsoft only shows you how to create a JsonResult via the Json method on MSDN
Note that the same is probably true with methods like View, Content, and File.
Fight all week unable to find an answer until you ask the question somewhere... Within 30 minutes of asking I found this: http://bob.ippoli.to/archives/2005/12/05/remote-json-jsonp/ which was exactly what I needed.
Thanks to all who posted.

Angularjs get Json from $routeParams

I have a controller which will save address data and will change the location (using $location.path("/checkout/"+ $scope.checkOutAddress);)to the next page with the json response as parameter by
$routeProvider.when('/checkout/:checkOutAddress', {
templateUrl : 'partials/checkOut.html',
controller : 'myController'
});
In the checkout controller trying to get the value using the below code
mCommerceApp.controller('myController', function($scope,$sessionStorage,$location,$routeParams,MCommerceService) {
$scope.checkOutAddress=$routeParams.checkOutAddress;
console.log($scope.checkOutAddress);
});
So now the problem is I am not able to get the json value. It is coming as an object. The browser log displays [object Object]. Any help how to get the $routeparama as json?
Thanks.
try to stringify it
var json = JSON.stringify($scope.checkOutAddress);
but i'm not sure it's the good way to pass data from controller to another, you can use a provider to stock datas.
App.provider('Data', function() {
//Properties declaration
this.tosend = '';
//Setters
this.setTosend = function(tosend) {
this.tosend = tosend;
};
//Getters
this.getTosend = function() {
return this.tosend;
};
});

calling controller from method from JavaScript

I am developing a web site using MVC 3 razor, in which I have the following situation:
A controller method:
public ActionResult MyControllerMethod(int parameter){
''go to bd a do some staff
IList<My_Custom> datafromDB = MyService.GetData(parameter);
'returns to my string tuped view
return View(datafromDB );
}
A strong typed view in which I use JavaScript:
#model IList<My_Custom>
<script type="text/javascript">
function getData()
{
var parameter = document.getElementById('myParamater').value;
$.get('/MyController/MyControllerMethod/' + parameter, function (data) {
loadData();
}
);
}
function loadData()
{
clearData();
datos = #Html.Raw(Json.Encode(Model));
//do some stuff with datos
}
</script>
The JavaScript call to the controller works fine but my problem is that the string typed view seems like is not taking the new value for the #model, so keeps loading the same information.
Although I have debugged the action controller and it returns different data every time.
So is there any way to refresh the Model value of a string typed view?
I also tried to process the data value of that line
$.get('/MyController/MyControllerMethod/' + parameter, function (data) {
but I wasn't successful doing that.
Your action return view, that's why nothing works. How your code works:
Load data in action, then generate view with json on the page
Send requst to the server and receive html with json (all this data are in memory),
then you access json from first step
How it must work:
Create view
Send request to the server (another method, that returning Json)
Access data
public ActionResult YourJsonAction(int parameter)
{
IList datafromDB = MyService.GetData(parameter);
return Json(datafromDB, JsonRequestBehavior.AllowGet);
}
function getData()
{
var parameter = $('#myParamater').val();
$.get('/MyController/YourJsonAction/' + parameter, function (data) {
//data from YourJsonAction
});
}

Spring MVC send a String from the client to controller using DOJO

I have the following Code on my Client
var value = {"userId":form.userId.value};
var xhrArgs = {
url : messageUrl,
handleAs : "text",
content: value,
load : displayMessages,
error : function(error) {
dojo.byId("displayArea").innerHTML = "Error aquiring messages";
}
};
dojo.xhrGet(xhrArgs);
}
And on my server side controller code
#RequestMapping(value = "/getMessages.htm", method = RequestMethod.GET)
public #ResponseBody String showMessageTable(#RequestParam("userId") String userId,ModelMap params)
{
I am getting a 400 error saying
The request sent by the client was syntactically incorrect ()
Could someone explain what i'm doing wrong? I have tested the dojo code with firebug and the value seems to be passing just fine. Thanks!
It might be helpful. visit to this URL : http://maxheapsize.com/2010/07/20/spring-3-mvc-ajax-and-jquery-magic-or-better-simplicity/

Categories