Spring MVC Not getting back any results with ajax request - javascript

I want to get data about my user from ajax request. But it never logs anything, which means it never reaches to success part of ajax request.
This is my controller
#Controller
#RequestMapping(value = "/api/profile")
public class ProfilController {
#Autowired
public UserService userService;
#RequestMapping(value = "/show/{username}", method = RequestMethod.GET)
public ResponseEntity<UserDTO> showData(#PathVariable String username) {
User u = userService.findByUsername(username);
if(!userService.findAll().contains(u))
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(new UserDTO(u), HttpStatus.OK);
}
}
And this is my java script file.
$(document).ready(function() {
console.log(localStorage.getItem('loggedIn'));
var usrnm = localStorage.getItem('loggedIn');
$.ajax({
url: "http://localhost:8080/api/user/login/check/"+usrnm,
type: "GET",
headers: {"Authorization": localStorage.jwt},
success: function(data) {
console.log('success');
}
})
$.ajax({
url: "http://localhost:8080/api/profile/show/"+usrnm,
type: "GET",
success: function(data) {
console.log('This part is not executed');
}
})
});
I am new to Spring, actually I am new to programming so sorry if this question is not well formatted

You may have an error in the showData function. You should do the following:
#PathVariable("username") String username

Try to remove this.
#Controller
#RequestMapping("/api/profile") // fixed this!!! remove `value = `
public class ProfilController {
#Autowired
public UserService userService;
#RequestMapping(value = "/show/{username}", method = RequestMethod.GET)
public ResponseEntity<UserDTO> showData(#PathVariable String username) {
User u = userService.findByUsername(username);
if(!userService.findAll().contains(u))
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(new UserDTO(u), HttpStatus.OK);
}
}

Related

Error while creating object to be consumed in in asp.net core controller

I'm having error when creating an object in javascript
I'm having this generic error:
Uncaught SyntaxError: Invalid or unexpected token
That's why i can't solve it. it didn't have specific error message.
This is my model
[Serializable, JsonObject]
public class CompleteOrderRequest : BaseMessageRequest<CompleteOrderRequestDto>
{
}
[Serializable]
[JsonObject, Bind("RequestFrom,RequestBy")]
public abstract class BaseMessageRequest<T> : IBaseMessageRequest<T> where T : class, new()
{
protected BaseMessageRequest()
{
Request = new T();
}
[Required, StringLength(255, MinimumLength = 3)]
[BindProperty(SupportsGet = true), BindRequired]
[FromQuery]
public string RequestBy { get; set; }
[BindProperty(SupportsGet = true)]//, BindRequired]
[FromQuery]
public T Request { get; set; }
}
public class CompleteOrderRequestDto
{
public string OrderNo { get; set; }
}
This is my controller
public async Task<IActionResult> PayNow([FromBody] CompleteOrderRequest request)
{
return View();
}
And this is my javascript code.
var CompleteOrderRequest = {};
CompleteOrderRequest.RequestBy = 'test';
$.ajax({
type: 'POST',
url: '/Orders/PayNow/${CompleteOrderRequest}',
success: function (data) {
if (data.success) {
}
}
});
The error is in this line. I'm encountering error before calling the controller.
CompleteOrderRequest.RequestBy = 'test';
So what's wrong with what Am i doing? And I'm receiving this error
Uncaught SyntaxError: Invalid or unexpected token
When creating your object in JavaScript, you can declare the properties inline like this:
var CompleteOrderRequest = {
RequestBy: "test"
};
You'd also need to ensure you provide that object as the data parameter when posting with ajax.
fix the ajax
$.ajax({
type: 'POST',
url: '/Orders/PayNow',
data: { request: CompleteOrderRequest}
success: function (result) {
if (result.success) {
}
}
});
and when you use only one kind of data from ajax , you don't usually need [FromBody]. Try to change the action too
public async Task<IActionResult> PayNow(CompleteOrderRequest request)
Since you use [FromBody] in action,you need to change your contentType to application/json and convert CompleteOrderRequest to json type:
var CompleteOrderRequest = {};
CompleteOrderRequest.RequestBy = 'test';
$.ajax({
type: 'POST',
url: '/Orders/PayNow',
data: JSON.stringify(CompleteOrderRequest),
contentType:"application/json",
success: function (data) {
if (data.success) {
}
}
});

how to call method with variable from javascript

I have this code that is not running in asp.net core 3.1 I need to send a variable to the method GetClientCaseType() it give error in #Model.GetClientCaseType[myInt] myInt if i put 1 or any number it works fine while for variable it give error
function casetype(value)
{
var myInt = parseInt(value.options[value.selectedIndex].value);
var casetype |"= '#Model.GetClientCaseType[myInt]';
alert(casetype + ' = ' + myInt.toString());
$("#ClientCase_cCaseType").val(casetype);
}
in .cs page
public string GetClientCaseType(int? myInt)
{
return something;
}
Any Solution please help thanks in advance
I tried ajax with no result 'error'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using WebLawyer1.Data;
using WebLawyer1.Models;
namespace WebLawyer1.Pages.ClientCases
{
public class CreateModel : PopulateClientCasePageModel
{
private readonly WebLawyer1.Data.LawyerDbContext _context;
public CreateModel(WebLawyer1.Data.LawyerDbContext context)
{
_context = context;
}
public IActionResult OnGet()
{
PopulateClientInfosDropDownList(_context);
PopulateCaseTypesDropDownList(_context);
return Page();
}
[BindProperty]
public ClientCase ClientCase { get; set; }
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
//if (!ModelState.IsValid)
//{
// return Page();
//}
//_context.ClientInfo.Add(ClientInfo);
//await _context.SaveChangesAsync();
//return RedirectToPage("./Index");
var emptyClientCase = new ClientCase();
if (await TryUpdateModelAsync<ClientCase>(
emptyClientCase,
"clientcase", // Prefix for form value.
s => s.iClientInfoID, s => s.iCaseTypeID, s => s.cCaseType, s => s.cPart,
s => s.iSequence, s => s.cKeyCase, s => s.dDate, s => s.cTitle,
s => s.cNote, s => s.cDetail, s => s.nFees, s => s.lWinFail, s => s.lClosed))
{
_context.ClientCase.Add(emptyClientCase);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
// Select CategoryID if TryUpdateModelAsync fails.
PopulateClientInfosDropDownList(_context, emptyClientCase.iClientInfoID);
PopulateCaseTypesDropDownList(_context, emptyClientCase.iCaseTypeID);
return Page();
}
public ActionResult GetUploadedFile(int id)
{
var result = _context.CaseType.Where(x => x.iCaseTypeID == id).First();
return Json(result.cCaseType);
}
}
}
<script>
function casetype(value) {
var id = parseInt(value.options[value.selectedIndex].value);
$.ajax({
url: '#Url.Action("GetUploadedFile", "Create")',
type: "POST",
data: JSON.stringify(id),
contentType: "application/json",
datatype: "json",
success: function (data) {
if (data != null) {
var vdata = data;
$('#ClientCase_cCaseType').val(vdata.id);
}
}
});
}
</script>
Actually, you can't do this. The reason is that they do not "live" in the same time. Javascript code is available only after C# / Razor is rendered. Refer to this thread.
So, I think you should use ajax here to send a request to access GetClientCaseType() method.
Update:
For how to send a ajax post request, you need to do the below steps:
1.Add the below service in stratup.cs
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
2.Add the AntiForgeryToken to the current page
#Html.AntiForgeryToken();
3.Set the token to request header in ajax
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
This is an example:
Create.cshtml:
#page
#model RazorApp.Pages.ClientCases.CreateModel
#Html.AntiForgeryToken();
<button id="btn" onclick="casetype()">Click</button>
#section scripts{
<script>
function casetype() {
var id = 1;
$.ajax({
url: 'Create?handler=GetUploadedFile',
type: "POST",
data: { id : id },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
if (data != null) {
var vdata = data;
}
}
});
}
</script>
}
Create.cshtml.cs:
public class CreateModel : PageModel
{
public void OnGet()
{
}
public IActionResult OnPostGetUploadedFile(int id)
{
var result = "AAA";
return new JsonResult(result);
}
}
Note: the pagehandler should be in this format OnPostXxx() or OnGetXxx().
And the url in ajax should like XXX?handler=Xxx.
Result:

Pass ID list using ajax call to ViewModel with JQuery

In my web service (order.asmx) I have a method which accept a viewmodel as a parameter. Method signature is below.
public string CreateOrder(OrderModel order)
and my order.cs is like below,
public class OrderModel: BaseClass
{
public OrderModel()
{
this.RestaurantIDs = new List<long>();
}
public long OrderID { get; set; }
public List<long> RestaurantIDs { get; set; }
}
I'm passing all the order related details using ajax call to this service method. To pass the RestaurantIDs I'm using an array which gives me 500 server error. I tried with stringify as well but didnt work. Anyone can help me with this?
ajax call
function createOrderObject()
{
var order = new object;
order.CustomerName = $("#txtName").val();
order.RestaurantIDs = selectedRestaurants.map(function (obj) {
return obj.RestaurantID;
});
}
// here the selectedRestaurants is object array.
function createOrder()
{
var order = createOrderObject();
var url = '/Service/OrderService.asmx/CreateOrder';
var dataSet = '{orderModel:' + JSON.stringify(order) + '}';
var orderInfo = $.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: url,
data: dataSet,
dataType: "json",
error: function () {
giveNotification({ NotificationCode: 500, Message: "Internal Server Error, Please try again." });
loadingImg(ele, "hide");
});
}
the error message }

Ajax post request in Spring MVC

I am currently trying to call an ajax request from a JavaScript onchange handler to call a Spring MVC controller. I believe the way I am currently calling the URL in my view is wrong since I get an 404 error on the browser when the event is triggered and call for url. Can anyone shine some light if I have everything setup correctly?
Here is my code:
#Controller
public class DataTableController
{
#RequestMapping(value = "/table", method = RequestMethod.GET)
public String home(Model model) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> gpnList = new ArrayList<GPN>();
gpnList.add("GPN-1"); gpnList.add("GPN-2"); gpnList.add("GPN-3");
model.addAttribute("gpnList", mapper.writeValueAsString(gpnList));
return "index"; //name of my view
}
#RequestMapping(value = "/getsector", method = RequestMethod.POST)
public #ResponseBody String getSector(#RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> sectors = new ArrayList<String>();
sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(sectors);
}
}
Jquery Code:
$(document).ready(function()
{
document.getElementById("markets").onchange = function()
{
var market = $("select[id='markets'").find('option:selected').text();
var filters = { "market" : market }
filters = JSON.stringify(filters);
$.ajax({
url: "/getsector",
type: "POST",
dataType : 'json',
contentType : "application/json",
data: JSON.stringify(filters),
success: function(response)
{
console.log("sucess!");
},
error: function(e){
console.log("ERROR: ", e);
}
});
}
});
The main thing I want to achieve is being able to call my controllers via ajax calls. Any other tips on Spring Controller Mapping and conventions will be appreciated.
If your a requesting information you should use GET requests, not POST.
You are mixing #RequestParam with a json payload. If you want to receive your filter as a request param it has to go at the url, not as a json payload, using something like:
$(document).ready(function()
{
document.getElementById("markets").onchange = function()
{
var market = $("select[id='markets'").find('option:selected').text();
$.ajax({
url: "/getsector?market="+market,
type: "GET",
success: function(response)
{
console.log("sucess!");
},
error: function(e){
console.log("ERROR: ", e);
}
});
}
});
#RequestMapping(value = "/getsector", method = RequestMethod.GET)
public #ResponseBody String getSector(#RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
.... your logic.
}
On the other hand, if you really want to use POST requests with a json payload, you need to use #RequestBody at the controller and bind the json object to a bean with the same properties.
#RequestMapping(value = "/getsector", method = RequestMethod.POST)
public #ResponseBody String getSector(#RequestBody Market market) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> sectors = new ArrayList<String>();
sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
return sectors;
}
public class Market
{
String market;
//getter and setter...
}
Bear in mind your javascript is wrong as well, you are using JSON.stringify twice.
If you use #ResponseBody and spring is configured fine it will make the serialisation for you when returning the response, so you do not have to do it manually.
This code has not been tested, it is just for you to get an idea.

How to access Model Data in Ajax response

I have two forms, consider Form1 and Form2, both are MVC forms only. These forms using two different view models as shown below :
public class Form1ViewModel
{
//some public properties
public string QueryString { get; set; }
}
public class Form2ViewModel
{
//some public properties
public string PreviousQueryString { get; set; }
}
In the controller Post Action I'm writing like this :
[HttpPost]
public ActionResult ProcessForm1(Form1ViewModel form1Obj)
{
//some logic goes here
//I'm preparing Querystring from form1 data and appending to Form2 model like
Form2ViewModel form2Obj=new Form2ViewModel();
form2Obj.PreviousQueryString = form1Obj.QueryString;
return View("Form2",form2Obj) ;
}
And in Form1, I'm submitting through Jquery Ajax as
frm.submit(function(ev) {
var formData = frm.serialize();
$.ajax({
type: "POST",
url: 'ControllerName/ProcessForm1',
data: formData,
success: function(response) {
//Here i need to read the PreviousQueryString and need to push to window.history.pushState()
}
error: function() {}
});
});
In the Ajax success, I need to read the PreviousQueryString from the response.
I knew how to do it client side(using pure JS) but it's my requirement.
How can I do it?
Try this
[HttpPost]
public string ProcessForm1(Form1ViewModel form1Obj)
{
JavaScriptSerializer js = new JavaScriptSerializer();
Form2ViewModel form2Obj=new Form2ViewModel();
form2Obj.PreviousQueryString = form1Obj.QueryString;
return js.Serialize(form2Obj);
}
success: function(response) {
var objResponse = $.parseJSON(response);
if (objResponse.PreviousQueryString != "") {
alert(objResponse.PreviousQueryString);
}
}

Categories