How to make Rest Spring work with JS - javascript

Folks
I have a problem with consuming a rest using javascript.
This Rest is already being used in other applications, where PHP and Aspx conserve the same described below.
#Controller
#RequestMapping("/userlogin")
public class UserRest {
#Autowired
private UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<RetornUser> login(#RequestBody User user) {
RetornUser retornUser = new RetornUser();
try {
user = userService.autenticarUsuario(user);
retornUser.setUsuario(usuario);
retornUser.setCodigoRetorno(1);
} catch (Exception e) {
retornUser.setCodigoRetorno(-1);
retornUser.setMensagem(e.getMessage());
}
return new ResponseEntity<>(retornUser, HttpStatus.OK);
}
}
The code above works perfectly with PHP, Aspx and Java calls.
When I call the routine, the JS is falling into the error function before receiving the return.
The worst thing is that the JS error is not bringing the reason. Below the code in pure HTML.
function logar() {
try {
var json = JSON.stringify(usuario);
json = "{\"nome\": \"garra\",\"senha\": \"1234\"}";
$.ajax({
type: "POST",
url: "http://localhost:8080/garrasystem/webservice/userlogin/login",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 300000, // sets timeout to 3 seconds
success: function (retorno) {
alert(retorno);
},
error: function (data, textStatus, xhr) {
alert(data.responseText);
}
});
} catch (e) {
console.log(e);
}
}
The way it is there, when I send debug, it calls the normal login method, but it falls into the error function, nor does it expect the login method to perform the return.
I put the method return String only and nothing too.
My Spring is 4.
I'm waiting for some help
Vinicius Castro

Looks like you are passing string instead of json object. Could you try passing the following:
var data = {
nome: "garra",
senha: "1234"
};

Folks
Being focused on a single problem, I forgot to analyze the button type. It was like type submit, so it was not working. It is like experiencing these kind of mistakes.
Thank you to all who supported me

Related

Getting 500 server error from Ajax call to a SOAP web method in .Net

I have two different async calls I am doing with ajax. Both are done the same way, but the one has parameters for the web method. The link is correct, when I follow it I get the return correctly in the browser, but I just keep getting a server 500 error. Any ideas?
The one works fine without parameters, here is the JS/jQuery code since I am slightly sure it isn't on the C# side:
function CatChanged() {
var strA = $('#ddlCategory').val();
$.ajax({
url: encodeURI('https://localhost:44380/WebService1.asmx/GetProducts?category=' + strA),
data: '<soap: Envelope xmlns: xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd="http://www.w3.org/2001/XMLSchema" xmlns: soap="http://schemas.xmlsoap.org/soap/envelope/%22%3E<soap: Body><xmlns="http://tempuri.org/" /></soap: Body></soap: Envelope >',
type: 'POST',
contentType: "text/xml",
dataType: "text/xml",
success: function (response) {
alert(response.responseText);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR!!");
alert(xhr.status);
alert(thrownError);
}
});
}
Here is the web method code from the C# code behind:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string GetCategories()
{
Catalog cat = new Catalog();
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(cat.categories);
}
[WebMethod]
public string GetProducts(string category)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
Catalog cat = new Catalog();
List<string> retList = new List<string>();
switch (category)
{
case "Electronics":
foreach (Product product in cat.electronicProducts)
{
retList.Add(product.itemName);
}
return jss.Serialize(retList);
case "Apparel":
foreach (Product product in cat.apparelProducts)
{
retList.Add(product.itemName);
}
return jss.Serialize(retList);
case "Food and Drink":
foreach (Product product in cat.electronicProducts)
{
retList.Add(product.itemName);
}
return jss.Serialize(retList);
default:
foreach (Product product in cat.electronicProducts)
{
retList.Add(product.itemName);
}
return jss.Serialize(retList);
}
}
...
Here is a screenshot of the return I get in the browser when I follow the direct link from the developer's console in Chrome:
The return is all good from the web method when called from the url. In which leads me to think that it has to be something in the ajax call, and i'm not sure what I need to do different in order to consume it when I add the parameter to the web method. Like I said, the first web method works in my JavaScript code, and I was able to parse everything from the return just fine.
Also, using any other services, MVC, or anything like that isn't an option. I have to make it work given the current situation.
Alright so if i understand you correctly. When you visit the URL with your browser the results work just fine. But when you do an ajax call you're having troubles.
The one thing i noticed from your code is that you're doing a POST request with your ajax call but the methodes are both GET. Try changing the type within your ajax call to GET.
E.g.
function CatChanged() {
var strA = $('#ddlCategory').val();
$.ajax({
url: encodeURI('https://localhost:44380/WebService1.asmx/GetProducts?category=' + strA),
data: '<soap: Envelope xmlns: xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd="http://www.w3.org/2001/XMLSchema" xmlns: soap="http://schemas.xmlsoap.org/soap/envelope/%22%3E<soap: Body><xmlns="http://tempuri.org/" /></soap: Body></soap: Envelope >',
type: 'GET', // <-- Changed from POST to GET
contentType: "text/xml",
dataType: "text/xml",
success: function (response) {
alert(response.responseText);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR!!");
alert(xhr.status);
alert(thrownError);
}
});
}

How to call a cs function in another library with ajax

Im working with the model view/Controller, so im trying to keep files in different folders like this
Im trying to call a c# class on the Business folder from the Boleta proyect with ajax within a aspx like this.
$.ajax({
type: "POST",
url: "Business/SaveExpenses.cs/save",
data: JSON.stringify({ questions: questions}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
console.log(data);
},
error: function (data) {
alert("fail");
}
});
The c# file that im trying to call looks like this.
namespace Business
{
public class SaveExpenses
{
public string save(string foo)
{
string ret= "something";
return ret;
}
}
}
When the page is executed and goes through the ajax function it throws an error 404 not found.
Now my question is, how do I navigate the folders in asp.net? or the correct way of calling the function.
Im comming from a php environment and im pretty new to asp.net so i will gladly take any suggestions
This url is wrong:
url: "Business/SaveExpenses.cs/save"
The URL should refer to the actual route. For example:
public class BusinessController : Controller
{
// GET
public ActionResult Index()
{
return View();
}
public string Save()
{
string ret= "something";
return ret;
}
Then your URL would be Business/Save(subject to RouteConfig etc considerations).
In Boleta project add the namespace of business
using Business;
then create one action in controller into Boleta Project
public JsonResult Save(param)
{
SaveExpenses se = new SaveExpenses();
var result= se.Save(param);
return json(result);
}
and call save() action through ajax
look into Adding a Web API Controller. basically, your ajax call will hit a http endpoint in which you'll execute your server side logic there.
The following is just a generic pattern - you'll need to implement a bit more plumbing to get this functional...
$.ajax({
type: 'POST',
url: '/Business/Expenses', // http route
// [...]
});
[RoutePrefix("Business")]
public class ExpensesController : ApiController
{
[HttpPost]
public IHttpActionResult Save([FromBody] string questions)
{
// do stuff
return Ok("something");
}
}

Post Ajax call says Get not allowed

I'm trying to use ajax with post method but it keep poping me this error
An attempt was made to call the method \u0027SendEmail\u0027 using a GET request, which is not allowed
Here is the js
var obj = { name: name, company: company, country: country, email: email, msg: Msg }
var json = JSON.stringify(obj);
$.ajax({
method: "POST",
url: "ContactUs.aspx/SendEmail",
contentType: "application/json; charset=UTF-8",
data: json,
dataType:"json",
success: function (data) {
var a = 3;
},
error:function(a,b){
var a = 43;
}
})
and here is the server side on c#
[WebMethod]
public static void SendEmail(string name, string company, string country, string email, string msg)
{
}
Thanks in advance!
You should follow this way:
Your backend method which you already decorated with [WebMethod] and added a reference of using System.Web.Services;, I've changed the method to return something so it can be verified whether it works or not.
[WebMethod]
public static String sendEmail(string param)
{
return "Your String";
}
within your .aspx page, add scriptManager for enabling client side calling to your code behind methods
<asp:ScriptManager ID="scriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
Finally within your JQuery script, call the method like this:
$(document).ready(function () {
PageMethods.sendEmail("", onSuccess);
function onSuccess(response)
{
alert(response);
}});
Hope it helps!
Try to use [HttpPost] instead of [WebMethod] and remove static.
Is it a REST API or MVC?

Call c# function with javascript code

I would like to call a code behind function from the client side.
The function cannot be static - should modified unstatic variabels.
I was able to create a non-visible button, and when I need that function I demonstrate a click on that btn.
How can I send parameters to that code behind function?
$.ajax({
url: '/ControllerName/ActionName',
type: "GET",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
}
});
This is the client side to call backend method. The server side to accept this request:
public ActionResult ActionName(string param1)
{
return View(param1);
}
In this case, we used jQuery, the javascript plugin, and we used AJAX request, also sending parameters.
Using MVC and jQuery
Client Side ( Using Razor )
$.ajax({
url: '#Url.Action("ActionName","ControllerName",new{parameters})',
type: "GET",
contentType: "application/json",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
},
error: function (jqXHR, error, errorThrown) {
console.log('An error as occured');
},
});
Server Side
[HttpGet]
public JsonResult ActionName(string param1)
{
return Json(param1, JsonRequestBehavior.AllowGet);
}
Note: HttpGet Verb is the default verb for every ActionResult/JsonResult
the button have a CommandArgument attribute that you can use to send a value to that function and you can read it as follow :
public void yourFunction(object sender,Eventargs e)
{
string args = ((LinkButton)sender).CommandArgument.ToString();
// rest of code here
}

Trying to get a JQuery Post to communicate with WCF, but the JSON data is not being accepted

I am using the following JQuery\JavaScript code to communicate with a WCF 4 REST service.
<script>
var serviceUrl = "http://services.xiine.com/Xiine/Live/AccountService/rest/json/Login";
var userInfo = {
"IsNotEncrypted":true,
"Password":null,
"UserName":null
};
var loginSuccess = function(data, textStatus, jqXHR){
console.log("yay");
};
var loginError = function(){
console.log("oh no");
};
$.post(serviceUrl , userInfo, loginSuccess);
$.post(serviceUrl , loginSuccess);
</script>
I am trying to establish why it is that the service will correctly return a false value when I do not pass the user data:
$.post(serviceUrl , loginSuccess);
As opposed to when I do pass user data, at which point it gives a POST 400 (Bad Request) error.
$.post(serviceUrl , userInfo, loginSuccess);
I am sure it has to do with how the JSON object, userInfo, is being built or interpreted, and I can post Fiddler 2 or WireShark dumps, if that will help. Just let me know...
I don't really have access to changing the WCF side of the service, so hopefully there is something I can do on my end to make this work.
Thanks!
Edit
I got a little more information... Apparently, the problem is that the server is responding with the following error:
The server encountered an error processing the request. The exception message is 'The incoming message >has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', >'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the >documentation of WebContentTypeMapper for more details.'. See server logs for more details. The >exception stack trace is:
at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
So I am thinking I need to figure out how to get the object to go across the wire as a JSON object via a JQuery.post() method.
More information --- Again...
ok... There is no app.config or web.config, as such.
Here is what I can get as far as the contracts and code and what-not.
[ServiceContract]
public interface IAccount
{
[OperationContract]
bool Login(UserInformation user);
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AccountService : IAccount
{
public bool Login(UserInformation user)
{
//stuff...
}
}
[DataContract]
public class UserInformation
{
[DataMember(IsRequired = true)]
public string UserName;
[DataMember(IsRequired = true)]
public string Password;
[DataMember(IsRequired = true)]
public bool IsNotEncrypted;
}
public interface IUserInformation
{
UserInformation UserInformation { get; set; }
}
So, I found the answer to my question.
Someone attempted to point me in the right direction with a mention of the JSON.stringify() method, but it took me a little effort to get it implemented correctly.
In the end, I used WireShark to sniff out the http request, see what was actually being sent and received, and observe that not only did I need to stingify the data, but I also needed to specify the content type.
Here is the final code.
// This is the URL that is used for the service.
var serviceUrl = "http://services.xiine.com/Xiine/Live/AccountService/rest/json/Login";
// This is the JSON object passed to the service
var userInfo = {
"UserName": null,
"Password": null,
"IsNotEncrypted": true
};
// $.ajax is the longhand ajax call in JQuery
$.ajax({
type: "POST",
url: serviceUrl,
contentType: "application/json; charset=utf-8",
// Stringify the userInfo to send a string representation of the JSON Object
data: JSON.stringify(userInfo),
dataType: "json",
success: function(msg) {
console.log(msg);
}});
in the interface for your service, you need to have the OperationalContract attribute and in that attribute, you need to set the RequestFormat. Here is an example of what it might look like.
[OperationContract, WebInvoke(UriTemplate = "/runGenericMethodJSON", Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]

Categories