How to POST data from AngularJS to Struts 2 using REST - javascript

I need to get the value from client side to server side. I am using AngularJS and Struts2 REST.
My controller doesn't get the value passed or am I wrong in passing or using RESTful controller?
Here is my code:
angularcontroller.js:
app.controller('saveAddCatCtrl', function($scope, $http){
$scope.save = function(newAddCat){
$http({
method: "POST",
url: "api/additionalcategory",
data: $scope.additionalCategory.addCatName
}).success(function(data, status, header, config){
//success
}).error(function(data, status, header, config){
//error
});
}
});
Here is my REST controller:
public class AdditionalcategoryController extends ActionSupport implements ModelDriven<Object>{
private AdditionalCategoryRepository additionalCategoryRepository =
(AdditionalCategoryRepository)ServletActionContext.getServletContext()
.getAttribute("additionalCategoryRepository");
private List<AdditionalCategory> additionalCategories;
public AdditionalCategory additionalCategory = new AdditionalCategory();
private int id;
public HttpHeaders index(){
setAdditionalCategories(additionalCategoryRepository.findAllAdditionalCategory());
System.out.println("GET api/additionalCategory");
return new DefaultHttpHeaders("index").disableCaching();
}
public HttpHeaders create(){
additionalCategoryRepository.createAdditionalCategory(additionalCategory);
return new DefaultHttpHeaders("create").disableCaching();
}
public void setAdditionalCategories(List<AdditionalCategory> additionalCategories){
this.additionalCategories = additionalCategories;
}
#Override
public Object getModel() {
if (additionalCategories == null){
return additionalCategory;
}else{
return additionalCategories;
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<AdditionalCategory> getAdditionalCategories() {
return additionalCategories;
}
public AdditionalCategory getAdditionalCategory() {
return additionalCategory;
}
public void setAdditionalCategory(AdditionalCategory additionalCategory) {
this.additionalCategory = additionalCategory;
}
}

Since angular service http sends JSON, you can send a JSON object using data property. The JSON object will be deserialized to your model class properties because you are using ModelDriven or Action class properties otherwise.
Struts2 REST plugin is made to handle JSON content from the request. It's possible due ContentTypeInterceptor, which is called rest, be able to find JSON handler for the request. The JSON handler is guessed from the Content-Type header or .json extension to the file in the URL. You can use either ways, but second is easier.
Note:
URLs without a file extension the Struts2 REST plugin defaulting to handle xhtml content. So you can modify your code
$http({
method: "POST",
url: "api/additionalcategory.json",
data: {}
}).success(function(data, status, header, config){
//success
}).error(function(data, status, header, config){
//error
});

Related

json string on POST to MVC action method using AJAX is null

I am getting a hard time to find out why the string sent via AJAX request is null. Console.WriteLine(data) shows empty. Status is 200 OK. If I add some code to parse the string received, I get an error stating that JObject.Parse cannot be null. I don't know what am I missing. The javascript code is ok. The action method also seems ok, but my knowledge on Asp.Net Core and MVC is very scarce, so I am not sure. Can someone please point out what am I missing?
The javascript code:
let obj = {email: email_address.value};
let objStringified = JSON.stringify(obj);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=UTF-8',
data: objStringified,
url: '#Url.Action("ReturnCheckAccountDuplication")',
dataType: 'text',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("Keep trying", error);
}
});
C# code:
[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] string data)
{
Console.WriteLine(data);
JObject jObject = JObject.Parse(data);
string email = (string)jObject["email"];
bool emailExists = CheckAccountDuplication.Get(email);
string returnResult = emailExists.ToString();
return Content(returnResult);
}
The solution on the controller side is
public class AccountCheckModel
{
public string Email { get; set; }
}
[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)
{
string result = CheckAccountDuplication.Get(data.Email).ToString();
return Content(result);
}
Thanks to all the members who commented on my problem, especially John Glenn who provided a solution. I had been trying for several days but without success. My knowledge of Asp.Net Core is very poor indeed. Thank you very much.
The easiest solution is to create a model representing the JSON data that your controller will receive. For example, create a class like so:
public class AccountCheckModel
{
public string email { get; set }
}
Then, use it as the parameter for your controller method:
public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)
This is the preferred way to access the request body. To get the request body as a string, you have to jump through some serious hoops.
An alternative way to send your data via AJAX to your Controller:
var json = {
email: email_address.value
};
$.ajax({
type: 'POST',
data: {'json': JSON.stringify(json)},
url: '#Url.Action("ReturnCheckAccountDuplication")',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log("Keep trying", error);
}
});
And your Controller:
[HttpPost]
public ActionResult ReturnCheckAccountDuplication(string json)
{
Console.WriteLine(json);
JObject jObject = JObject.Parse(json);
string email = (string)jObject["email"];
bool emailExists = CheckAccountDuplication.Get(email);
string returnResult = emailExists.ToString();
return Content(returnResult);
}

Problem with jQuery post to ASP.NET Core controller

I have gone through this solution on stackoverflow but I couldn't solve my problem.
In HomeController I have a method named as Audit which I want to be posted from /Home/Index page's script through jQuery. The controller looks like:
public class HomeController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Audit([FromBody] JObject jObject)
{
if (jObject != null)
{
return Json("success");
}
return Json("failed");
}
}
In the /Home/Index pages's javascript file I have tried to post a JSON Object to that Audit in a way like this:
var auditData = {};
$(document).ready(function(){
var request = $.getJSON('http://www.geoplugin.net/json.gp', function (responseData, status) {
auditData = {
Latitude : responseData.geoplugin_latitude,
Longitude : responseData.geoplugin_longitude
};
$.post('Audit', auditData, function (response) {
console.log(response);
});
});
});
I want the auditData object to be posted as JObject in /Home/Audit but something is going wrong. I think there is problem either in controller or, in $.post method. How can I solve this problem?
Your post URL is wrong, and you need to name the data you're posting back as jObject as well to match what you defined in your controller.
$.post('#Url.Action("audit", "home", new { area = "" })', { jObject: auditData },
function (response) {
console.log(response);
});
There are multiple issues in your current code, check points below one by one:
As the suggestion from Rory, your request url is wrong, which should be Home/Audit
If you post request without antitoken, you should remove [ValidateAntiForgeryToken]
You should post request data with json instead of form data.
Code:
Client
#section Scripts{
<script type="text/javascript">
var auditData = {};
$(document).ready(function(){
auditData = {
Latitude : "l1",
Longitude : "l2"
};
$.ajax({
type: 'POST',
url: 'Home/Audit',
data: JSON.stringify(auditData),
success: function(data) { alert('data: ' + data); },
contentType: "application/json"
});
});
</script>
}
Server:
public class HomeController : Controller
{
[HttpPost]
//[ValidateAntiForgeryToken]
public JsonResult Audit([FromBody]JObject jObject)
{
if (jObject != null)
{
return Json("success");
}
return Json("failed");
}
}

Asp net core 2.0 controller handler not triggered via java-script ajax

I am trying to post some data to a razor controller, I have two post handlers as shown in the source, one is the default one, another is named "OnPostFormalDealerNameAsync", I tried to use it to handle some post request, but I failed many times, everytime it simply trigger the default one, no matter how I change the url in the javascript. I am pretty new to asp.net, so I hope some one can help me out. Many thanks.
function getFormalDealerName(e)
{
var token = '#GetAntiXsrfRequestToken()';
$.ajax({
type: "POST",
url: "/ShoesMarket/Shoes2Dealer/dealers",
headers:
{
"RequestVerificationToken": token
},
data: dealer_str,
success: function (response) {
if (response != null) {
} else {
alert("Something went wrong");
}
},
failure: function (response) {
alert(response.responseText);
},
});
}
namespace ShoesSystem.Pages.ShoesMarket.Shoes2Dealer
{
[Authorize]
public class IndexModel : PageModel
{
private readonly ShoesSystem.Data.ApplicationDbContext _context;
public IndexModel(ShoesSystem.Data.ApplicationDbContext context)
{
_context = context;
}
[HttpGet]
public async Task OnGetAsync()
{
...
}
[HttpPost]
public async Task<IActionResult> OnPostAsync()
{
...
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("Shoes2Dealer/Dealers")]
public async Task<IActionResult> OnPostFormalDealerNameAsync()
{
...
}
}
}
I solve the problem following the post here : http://www.c-sharpcorner.com/article/call-web-api-using-jquery-ajax-in-asp-net-core/
I create a api, and thing solved.

angularjs$http.get and java api call

I'm trying to make an angularjs $http.get request with parameters but it's not working due to syntaxt may be. Can you please
confirm what i'm doing wrong , maybe syntax is wrong in angularjs call or in java api method
$http.get(document.requestPathPrefix + "/home/my-api",
$scope.requestParametersObject
).then(
function(response) {
$scope.output = response.data;
},
function(response) {
$scope.retrieveErrorMssg = "Failed to retrieve required data.";
});
my parameters are like in this image
parameter object for api call
And in java api call like this
#RequestMapping(value = "/my-api", method = RequestMethod.GET)
public ResponseEntity<Collection<MyObjectResponse>> getMyObjResponse(#RequestBody final MyObjectRequest request)
{
Map<Integer,MyObjectResponse> oResponse = new HashMap<>();
try {
//Manipulation and db calls
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return new ResponseEntity<Collection<MyObjectResponse>>(oResponse.values(), HttpStatus.OK);
}
try ,
$http({
url: '/home/my-api',
method: "GET",
headers: {
'Content-type': 'application/json'
},
data: JSON.stringify(request)
}).success(function(data, status, headers, config) {
}).error(function(data, status, headers, config) {
return null;
});
If you are worried about syntax, take a look at this simple example and modify it to your need.
In JS, your http.get call should contain the URL and its parameters if any,
$http.get('getUserInfo',
{
params : {
'userEmail' : 'userEmail'
}
}).then(function(response) {
console.log(response);
});
If you are passing a parameter to the API call, ensure your Java controller or the service has the parameter defined to receive the same. Ideally the parameters should match between the call and the provider
For example, for the above API call, the spring controller should like below,
#RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
public #ResponseBody User getUserInfo(
#RequestParam("userEmail") String userEmail) {
// Do Something
}

How to model AJAX interaction with java spring controller

I am trying to model a simple ajax interaction between my javascript code and my server.
Client
data = {};
data.url = "google.com";
$.ajax({
type: 'POST',
url: "/first/second",
data: data,
cache: false
}).done(function(response) {
Console.log("hello");
});
Server
#Controller
#HttpOptions(sslHandling = SslHandlingOption.NON_SSL_REDIRECTS_TO_SSL)
public class myController {
#RequestMapping(value = "/first/second", method = RequestMethod.POST)
#ResponseBody
public Map<String, Object> returnURL(#RequestParam(value = "url") String URL) {
Map<String, Object> responseMap = new HashMap<>();
responseMap.put("url", URL);
return responseMap;
}
}
My Error
In the logs, I am getting a 500 (Internal Server error).
Constraints
This code is obviously dumbed down to not give away company info, but the following constraints must be adheared to:
Request method must be POST
the data must be passed to the server as shown (initialized as a blank object)

Categories

Resources