I have a razor view which calls a method on an MVC controller via Ajax. All is working except I am not receiving anything back even though I am returning a JSON result. The "data" element in the success portion is undefined.
Here is the Ajax call:
callback: function(result) {
if (result === true) {
$.ajax(
{
type: "POST", //HTTP POST Method
url: "AddEmployee", // Controller/View
data: { //Passing data
Name: $("#txtName").val(), //Reading text box values using Jquery
City: $("#txtAddress").val(),
Address: $("#txtcity").val(),
Phone: $("#txtPhone").val(),
SSN: $("#txtSsn").val(),
success: function (data) {
alert(data.ResponseMessage);
//$('<div>' + data + '</div>').appendTo('#divConfirm');
}
}
});
Here is my controller:
[HttpPost]
public JsonResult AddEmployee(EmpModel obj)
{
bool isSaved = AddDetails(obj);
Response response = new Response {ResponseMessage = "Success!"};
return Json(response);
}
You put wrong } in data, my friend:
Name: $("#txtName").val(), //Reading text box values using Jquery
City: $("#txtAddress").val(),
Address: $("#txtcity").val(),
Phone: $("#txtPhone").val(),
SSN: $("#txtSsn").val() },
success: function (data) {
alert(data.ResponseMessage);
//$('<div>' + data + '</div>').appendTo('#divConfirm');
}
Related
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');
}
});
}
I am unable to Deserialized my JASON Serialized FormData
Please review my code
///here its my JSON
$("#btn_pro_spc").click(function () {
var formdata = $("#Product_spec_from").serialize();
$.ajax({
url: '#Url.Action("UpdateProductSpecification", "LC_LabChecking")',
type: 'POST',
data: { formdata : formdata },
datatype:'json',
success: function (data) {
}
});
});
///here it controller
public JsonResult UpdateProductSpecification(string formdata)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
LabCheckingModel LCModel = jss.Deserialize<LabCheckingModel>(formdata);
return Json(jss);
}
I Am getting serialized data perfectly but unable to Deserialized :(
Invalid JSON Primitive
It is not necessary to use use JavaScriptSerializer to deserialize your model. The DefaultModelBinder will do all this for you. Change the script to
$("#btn_pro_spc").click(function () {
$.ajax({
url: '#Url.Action("UpdateProductSpecification", "LC_LabChecking")',
type: 'POST',
data: $("#Product_spec_from").serialize(), // change this
datatype:'json',
success: function (data) {
}
});
});
and change the controller method to
public JsonResult UpdateProductSpecification(LabCheckingModel model)
{
// the value of model will be correctly bound
return return Json(??);
}
Side note: not sure what you are trying to return (currently its an instance of JavaScriptSerializer which does not make sense)
I need to send data from the client html back to the spring controller.
I have a controller which generates a Json array whichh I sent via ajax to the html side when requested.
That functions well.
The Problem is I need to send the Json array back to another controller for evaluation and changes.
If I post the data and assign an class object of the original class I get the error " Bad request" and it didn't work.
If I assign an object in the controller which consumes the post. That works
but I get an hashmap for which I dont know how to access.
I cant cast it to another class nor access it to work with it.
Since I am new to this can someone give me an advice how to consume the post
on the receiving controller side.
Thanks
Khelvan.
Controller code ist stated below
controller 1 for Get
#RequestMapping("/Person")
#ResponseBody
public ArrayList<Person> ajax_Person_array()
{
ArrayList<Person> Dummy = new ArrayList<Person>();
for ( x=0; x < 5; x++ ){
Dummy.setName("Alfon");
Dummy.setID("5");
Dummy.setStree("Delta");
Dummy.setName("Neutral");
Person.add(Dummy);
}
return Dummy;
}
Controller 2 for post
#RequestMapping(value="/ajax", method=RequestMethod.POST, consumes = "application/json")
//public #ResponseBody String post( #RequestBody Object ajax_Person_array()) {
public #ResponseBody String post( #RequestBody ArrayList<Person> ajax_Person_array()) {
System.out.println("First TEST");
String Success = "OK";
return Success;
}
Html : get ajax
var ajax_data;
$.ajax({
url: "http://localhost:8080/Person",
async: false,
dataType:'json',
cache: false,
success: function (data) {
ajax_data = data;
alert("success ");
},
error:function(){alert("something went wrong ");}
});
}
Html post ajax
$.ajax({
url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'text',
data: ajax_data,
// data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});
#RequestMapping (value="/ajax", method=RequestMethod.POST, consumes = "application/json")
public #ResponseBody JSONObject post( #RequestBody JSONObject person) {
//Pass data to a service to process the JSON
}
For your ajax request, do not set dataType to 'Text'. Set it to JSON
$.ajax({ url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'json',
data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});
In my web api project, I got a controller named ContactController and a method named Synchro in it which waits for a list of string as below:
[HttpPost]
[Route("api/Contact/Synchro")]
public IHttpActionResult Synchro([FromBody]List<string> listNumTel)
{
List<Profil> listContact = new List<Profil>();
if (listNumTel.Count() > 0)
{
try
{
listContact = Librairie.Contacts.getContactSync(listNumTel);
return Ok(listContact);
}
catch(Exception e) {
return InternalServerError(e);
}
}
else
{
return BadRequest();
}
}
To test that method, I've created the ajax called below:
$("#btn_synchro").click(function () {
$.ajax({
url: '../api/Contact/Synchro',
type: 'POST',
data: {
"listNumTel": [
"+33640512999",
"+33640522997",
"+33640182998",
"+33640742996"]
},
dataType: 'json',
success: function (data) {
alert('Synchro réussi: ' + data);
},
error: function (request, error) {
alert("Erreur lors de la synchro");
}
})
});
When I test on debug mode, the call works fine but the method get a null list. I checked if the json is valid and it is. Does Somebody sees what could be wrong ? Thanks in advance !
Thanks for the answers, but I've just found out the solution. It was all about JSON sent. To send a list of string by an ajax call for example, the JSON should looks like below the variable listNumero
("#btn_synchro").click(function () {
var listNumero =
[ '+33640532999',
'+33640532997',
'+33640532998',
'+33640532996'];
$.ajax({
url: '../api/Contact/Synchro',
type: 'POST',
data: JSON.stringify(listNumero),
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('Synchro réussi: ' + data);
},
error: function (request, error) {
alert("Erreur lors de la synchro");
}
})
});
You can compare to my post, the JSON is different. Now my web api controller can get the values from the list.
I have a Spring MVC web application and I have the following web service.
#RequestMapping(value = "/newBill", method = RequestMethod.POST)
public #ResponseBody ModelMap acceptNewBill(#ModelAttribute ("Bill") Bill newBill ){
Bill bill = new Bill();
bill.setTableName(newBill.getTableName());
bill.setRoom(newBill.getRoom());
bill.setCovers(newBill.getCovers());
ModelMap model = new ModelMap();
model.put("status", true);
return model;
}
The following Script performs the front end functions.
$('.done').click(function(){
var jsonObject = createJSON(".newBill");
jQuery.ajax({
url: "/newBill",
type: "POST",
data: {bill: JSON.stringify(jsonObject) },
dataType: "json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});
});
function createJSON(elementToConvert) {
jsonObj = [];
$( elementToConvert + " input").each(function() {
var id = $(this).attr("class");
var email = $(this).val();
item = {}
item [id] = email;
jsonObj.push(item);
});
return jsonObj;
}
The above createJSON function go through a provided html element and puts the values into an object! The click function performs the POST and the Post contains the following data.
bill [{"tableName":"326432"},{"room":"3462346"},{"covers":"3426234"}]
Now when I debug and check the service, the data which goes from the front end doesn't get mapped in the parameter. I checked whether the variable names are the same as the POST. They are the same! but the values doesn't get mapped! Can any one please help me with this issue.
Update :
I changed the service method to GET and passed a value as a URL variable. Then it got mapped in the service param. The problem is in the POST.
Instead of using #ModelAttribute in your controller use #RequestBody:
public #ResponseBody ModelMap acceptNewBill(#RequestBody Bill newBill) {
On the ajax call, set the content type to application/json and stringify the whole object instead of just the array:
jQuery.ajax({
url: "/newBill",
type: "POST",
data: JSON.stringify({bill: jsonObject}),
dataType: "application/json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});