Call Web Service method that insert an object from jquery ajax - json

I have a web service method similiar to this:
#Path("/insert_update")
#POST
#Consumes({ MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_JSON })
public Object insert(User obj) {
...(insert and return object)
}
And I want to call this method from jquery, using ajax. I've tried something like this:
var rootURL = "http://Path/to/my/web/service";
function insertUpdate() {
var user = {'name' : $("#name").val(),
'surname' : $("#surname").val(),
'surname1' : $("#surname1").val(),
'usertxt' : $("#usertxt").val(),
'password' : $("#password").val() };
$.ajax({
url : rootURL + "/insert_update",
type : "POST",
contentType: 'json',
dataType : "json",
data : user,
success : function(data) {
alert(JSON.stringify(data));
},
error : function(data) {
}
});
}
Is this code correct? When I try to use it I get this response:
Failed to load resource: Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
XMLHttpRequest cannot load ... . Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
I hope you can help me.
Greetings.
UPDATE
The web service is in the same machine, but in other port. I run the web service project on a WebSphere Application Server and then I only open the HTML file to test my code.
I have other method I don't have problem with, like this:
#Path("/all")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Object all() {
...(get all users)
}
And the JQuery method for this code:
function all() {
$.ajax({
url : rootURL + "/all",
type : "GET",
dataType : "json",
success : function(data) {
$("#tabla tbody:last").empty();
$.each(data.data, function(i, item) {
$("#tabla tbody:last").append("<tr><td>"+item.id+"</td><td>"+item.name+
"</td><td>"+item.surname+"</td><td>"+item.surname1+"</td><td>"
+item.usertxt+"</td><td>"+item.password+"</td></tr>");
});
},
error : function(data) {
}
});
}
This works fine, I have no problem...but I had to donwload an extension for Chrome to test locally, Allow-Control-Allow-Origin.
Why with GET method I have no problem and with POST method yes???
Greetings.

Related

Calling a REST web service spring controller from a html page, and passing the form elements alone with the call using ajax

I have a controller that creates a new user for my application (users are stored using MongoDB). I ran the code with #Path and #RequestBody annotations successfully using postman tool.
Now I have to include a UI which is mapped to my controller. I tried passing the values using ajax, and the values are getting passed(upon inspection from my browser). But the controller is not being called.
Then I tried with #RequestMapping and #RequestBody annotations but then I am getting the following warning while accessing it through Postman
WARNING: No root resource matching request path /Task1_2/Create/createUser has been found, Relative Path: /Create/createUser.
Finally, I tried with all three annotations #Path,#RequestMapping and #RequestBody then I am getting a response in Postman.
All the above were done by directly calling the controller from Postman through the URI.
But still, now I am not able to get any response on my browser while calling the HTML page which is mapped to my controller.
This is my controller
#RestController
#Path("/Create/")
#RequestMapping("/Create/")
public class CreateUser {
#POST
#Path("createUser")
#RequestMapping(value="createUser",method=RequestMethod.POST,consumes="application/json")
public Response Create(#RequestBody String request)
{
.....
BasicDBObject obj = (BasicDBObject) JSON.parse(request);
.....
output = "#Produces(\"application/json\")"+"User Created Successfully";
return Response.status(200).entity(output).build();
}
And this is my ajax function
function fun()
{
var search = { UserName: $( "input[name='UserName']" ).val(),
FirstName: $( "input[name='FirstName']" ).val(),
LastName: $( "input[name='LastName']" ).val(),
Mobile: $( "input[name='Mobile']" ).val(),
EmailId: $( "input[name='Email']" ).val()
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/Create/createUser",
data: JSON.stringify(search), // Note it is important
success :function(output) {
alert(output);
},
error: function(e){
alert('failure');
}
});
}
I have kept the HTML file(CreateUser.html) with the above script inside the WebContent folder of my project.
So
1. What am I doing wrong?
2. Should I be using #Path alone with #RequestMapping
I think it is related to your JSON format which your are sending from Ajax.
This would run
function fun()
{
var search = { UserName: $( "input[name='UserName']" ).val(),
FirstName: $( "input[name='FirstName']" ).val(),
LastName: $( "input[name='LastName']" ).val(),
Mobile: $( "input[name='Mobile']" ).val(),
EmailId: $( "input[name='Email']" ).val()
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/Create/createUser",
data: JSON.stringify({search : search }), // Note it is important
success :function(output) {
alert(output);
},
error: function(e){
alert('failure');
}
});
}

405 Method not allowed using Resteasy and ajax

I am facing an issue while login . Registration is working fine.
Tech stack - HTML/AJAX/JQuery->Resteasy (Wildfly 10.1.0 Final)
I have the url - https://www.test.com/login.html - (actual URL name is modified)
When I am submitting the form with method type = "POST", it always throws, 405 Method not allowed.
Below is the section of the code:
submitHandler: function(form) { // fires only when form is valid
var loginData = formJSONLoginData();
$.ajax({
url:"https://"+getUrl()+"/curAuthService/curAuth/authenticateUser/v1",
type : "POST",
dataType : "json",
contentType: "application/json",
data: loginData,
success : function(response) {
},
error: function( xhr, status, error ){
}
});
return false;
},
And the Rest API is below:
#Path("/curAuth")
public class FHAuthResource {
#POST
#Path("/authenticateUser/v1")
#Produces("application/json")
#Consumes("application/json")
public String authenticateUser( AuthVO authVO ) {
}
}
It would be great help if someone can help/advice on where I am going wrong.
Registration is in similar format and it works fine.
Ultimate stupid mistake. Missed out "extends Application" for the Application file which is required for resteasy.

Can´t consume Json from MVC and Web API controller

I'm trying to consume json data from a web API in .NET. I tried by two ways, with web API and returning Json with a MVC controller but I can't consume from any of both. I only can consume it from a view inside my project, but when I try to consume with a html page outside my project it throws an error.
It is hosted in azure. Here is the code of the Action.
public ActionResult PreguntasById(int id)
{
var emp = db.pregunta_area.Where(i => i.fk_pregunta == id).Select(e => new
{
id = e.fk_pregunta,
pregunta = e.Preguntas.pregunta,
area = e.fk_area
}
).ToList();
return Json(emp, JsonRequestBehavior.AllowGet );
}
And my AJAX petition.
function siguientePregunta()
{
$("#pregunta").remove();
$.ajax({
type: "GET",
dataType: 'json',
url: 'http://carrierintegrator.azurewebsites.net/Preguntas/PreguntasById/'+contador,
async: true,
success: function (response) {
$("#pregunta-content").append("<h6 id='pregunta'>"+response[0].pregunta+"</h6>");
console.log(response);
},
error: function (obj, error, objError) {
alert("Error interno: " + objError);
console.log(id_pas);
}
});
contador++;
}
Also I tried to quit the dataType but it's useless. I don't know what it's going wrong.
I'm doign the same in the Web API Controller but i'm having the same error.

Append additional HTML result in calling MVC action by Ajax in DNN8

I'm new in DNN development.
I have created a very simple module in Visual studio--- A textbox and a button.
I just want to call the action in a controller by click the button, then show the return result in the textbox.
The code call the action success, but not sure why append lots of HTML inforation in the result.
Here is the action in the controller:
public ActionResult test1()
{
return Content("Return something");
}
Here is the Ajax code from the View:
$(document).ready(function () {
$("#btnSub").click(function () {
//alert(this.action);
$.ajax({
type:"GET",
contentType:"application/text",
url: "#Url.Action("test1", "Sky")",
data:"",
dataType: "text",
success: function (data) { $("#txtResult").val(data); alert("Success!") },
error:function(){alert("Failed!")}
});
});
});
And here is the result show in the textbox:
Anyone can let me know why the HTML information returned? Actually, I don't need it.
Thanks
Unfortunately, as described in DNN8 MVC unsupported features, it's not yet possible to return a JsonResult. So the solution I used is to return an ActionResult (although the function returns Json):
public ActionResult Test()
{
return Json(new { success = true });
}
On jquery side, I setup ajax call to receive result as html. This avoid the browser to display a parsing error. Finally, just need to remove the html part and manually parse the response. It's not very clean, but the only solution I found until DNN support JsonResult.
$.ajax({
url: '#Url.Action("Index", "Contact")',
type: 'POST',
dataType: 'html',
data: $('#contact-form input').serialize(),
success: function (response) {
jsonPart = response.substring(0, response.indexOf("<!DOCTYPE html>"));
var data = JSON.parse(jsonPart);
if (data.success) {
alert("Great");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error!");
}
});
EDIT : Improved solution
DNN8 now support IMvcRouteMapper. You can then register a route in RouteConfig.cs. Once done, you can call the function using following URL :
/DesktopModules/MVC/ModuleName/Controller/Action
The action can return a JsonResult. But pay attention, if you just call that function, it will fail with a null exception on ModuleContext. You have to include in the ajax call the following header :
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleContext.TabId,
"RequestVerificationToken": $("input[name='__RequestVerificationToken']").val()
}
You can find the module complete code here.
This is a working ajax call in DNN 9. You dont have to use #urlaction it will give whole html as well as data. dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action", this does the trick and don't forget to add the header otherwise it will throw 500 error.
$.ajax({
url: dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: "{ 'id':" + JSON.stringify(3543)+" }",
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleCon`enter code here`text.TabId,
"RequestVerificationToken":
$("input[name='__RequestVerificationToken']").val()
},
success: function (response) {
debugger;
},
error: function (errmsg) {
alert("Error!");
}
});
Your controller should be
[HttpPost]
public ActionResult ActionName(int id)
{
var data = id;
return BuidJsonResult(true,data);
}
Happy Coding :)

Passing in JSON array to spring MVC Controller

I am trying to pass a JSON array into spring MVC Controller like such:
var myList = new Array();
data._children.forEach( function (d) {
myList.push( {NAME: d.name, TYPE: d.TYPE, FDATE: d.FDATE } );
});
$.post("/ListRequest", {myList: myList});
The controller looks as such:
#RequestMapping(value="/ListRequest", method = RequestMethod.POST)
public void ListRequest(#RequestParam("myList") myList tempmyList )
{
System.out.println(tempmyList);
}
The class myList defined as such:
public class MyList {
private List<ListT> ListT;
public List<ListT> getListT() {
return ListT;
}
public void setListT(List<ListT> listT) {
ListT = listT;
}
}
ListT class:
public class ListT {
private String NAME;
private String TYPE;
private Long FDATE; ...
I keep getting this error:
HTTP Status 400 - Required myList parameter 'myList' is not present
Also tried this request:
$.ajax({
type: "post",
url: "ListRequest", //your valid url
contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
data: JSON.stringify(myList), //json object or array of json objects
success: function(result) {
//do nothing
},
error: function(e){
alert('failure');
}
but get this error: JBWEB000120: The request sent by the client was syntactically incorrect.
try to add this to you ajax call it should fix the unsupported response :
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
this is a full example of ajax call that is working for me :
$.ajax({
dataType : "json",
url : this.baseurl + "/dataList",
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
data : JSON.stringify(params),
type : 'POST',
success : function(data) {
self.displayResults(data);
},
error : function(jqXHR,textStatus,errorThrown ){
showPopupError('Error','error : ' + textStatus, 'ok');
}
});
Even I was facing same problem.
My client request was right and generated proper json file.
but still i was getting same error.
I solved this error using #JsonIgnoreProperties(ignoreUnknown = true) in pojo class.
refer this link.
Spring MVC : The request sent by the client was syntactically incorrect
You can try
#RequestParam("myList") myList tempmyList
#Param myList tempmyList
in addition, class names must begin with a capital letter.