404 Not Found in AJAX post call - javascript

I'm using Spring MVC and when I do an ajax post call I get a 404. My controller looks like this:
#Controller
#RequestMapping("/mensaje")
public class MensajeController {
public MensajeController() {
super();
}
#ResponseBody
#RequestMapping(value = "/prueba", method = RequestMethod.POST)
public String prueba(#RequestParam("cuerpo") final String cuerpo) {
String b = null;
String a = null;
return b;
}
}
And the ajax call like this:
<script type='text/javascript'>
$(document).ready(function() {
$("#save").click(function(e) {
e.preventDefault();
var myEditor = document.querySelector('#editor');
var html = myEditor.children[0].innerHTML;
$.ajax({
type : "POST",
url : "/Gestion-Practicas/mensaje/prueba",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: {'cuerpo': html},
async: false,
cache: false,
delay: 15,
success: function(data){
alert('success');
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
});
</script>
The url from where I do the ajax call is:
http://localhost:8080/Gestion-Practicas/mensaje/create.do
The url who appears in the Chrome's console after doing the ajax call is:
http://localhost:8080/Gestion-Practicas/mensaje/prueba
Summarizing, the ajax call never reaches the controller's method and I don't know why

Instead of #RequestParam use #RequestBody
#RequestParam - It's used for query parameters in request url.
#RequestBody - It's a post body payload.
Convert your String cuerpo to a class with property String cuerpo
public class PostBody{
private String cuerpo;
public String getCuerpo(){
return this.cuerpo;
}
public void setCuerpo(String cuerpo){
this.cuerpo = cuerpo;
}
}
Now your line public String prueba(#RequestParam("cuerpo") final String cuerpo)
Updated will look like public String prueba(#RequestBody final PostBody postBody).

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);
}

ASP.NET: Ajax doesn't send string

I have this method to send some data with ajax:
function SendData(foodID, basketID) {
var data = { FoodID: foodID, BasketID: basketID };
$.ajax({
url: '/Order/Post',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json;utf-8',
datatype: 'json'
}).done(function (data) {
console.log(data);
}).fail(function (data) {
console.log("Error: " + data);
});
}
In C#, my Post Method in my Order controller gets triggered, but the string I want to hand over is null:
public bool Post(string s)
{
//When this gets executed, s is null
return true;
}
I tested this by executing SendData(1,1) directly on a button click. What is the mistake I'm doing and how can I get the string in my Post-Method?
you are post the object. not string.
you can try generate to object and load this object. or add new one parameter to action (foodId and basketId but you must post like that if you check this option data:{foodId,basketId})
//model
public class SomeObject{
public string FoodId {get;set;}
public string BasketId {get;set;}
}
//code
public bool Post(SomeObject data)
{
return true;
}
It seems for me your data structure to the Post action doesn't match action parameter names. Try this:
[HttpPost]
public bool Post(string foodID, string baskedID)
{
return true;
}
I believe you have to name your data that's being passed like so:
data: { 's': JSON.stringify(data) }

WCF and Json Call

I am developing a WCF application and frontend uses JSON to call web methods.
I have a data model class as below
[DataContract]
public class GL_AccMainTypeListItem
{
[DataMember]
public int accMainTypeyNo { get; set; }
[DataMember]
public string mainType { get; set; }
[DataMember]
public int startAccNo { get; set; }
[DataMember]
public int endAccNo { get; set; }
}
My web method as below and return list of above objects. (These work well)
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GetDataString/{value}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public List<GL_AccMainTypeListItem> GL_AccMainType_GetAll()
{
DataAccessService da = new DataAccessService("usp_GL_AccMainTypeGetAll");
DataTable dt = da.ExecuteDataTable();
var acc = (from row in dt.AsEnumerable()
select new GL_AccMainTypeListItem
{
accMainTypeyNo = Utility.ToInt(row["accMainTypeNo"]),
mainType = Utility.ToString(row["mainType"]),
startAccNo = Utility.ToInt(row["startAccNo"]),
endAccNo = Utility.ToInt(row["endAccNo"])
});
return acc.ToList();
}
Basically here I used stored procedure and get a data table from database and return to client. I want to know how can I call this web service in client side using JQuery and iterate results set row by row.
<script src="jquery-1.11.2.js"></script>
<script>
$(document).ready(function () {
$('#btnGetAccountList').click(function () {
$.ajax({
//url will be yourclassname.svc/yourmethodname
url: 'namespaceofGL_AccMainType_GetAllmethod.svc/GL_AccMainType_GetAll',
method: 'Get',
contentType: "application/json;charset=utf-8",
success: function (data) {
//your account detail list will be here.
},
error: function (err) {
alert(err);
}
});
});
});
</script>
You have to make a ajax call to that method.
Eg:
// Function to call WCF Service
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function(msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}

AJAX call with parameters not working

I've got troubles making an ajax post with parameters to my controller. While this works:
$.post("../api/vorgang/blubb");
[HttpPost]
[Route(#"blubb")]
public void blubb()
{
// do amazing things here
}
The method is not being hit when I extend it for parameters:
$.post("../api/vorgang/blubb", { param1: "param1", param2: "param2"} );
[HttpPost]
[Route(#"blubb")]
public void blubb(string param1, string param2)
{
// method is not hit, why oh why
}
// the request text
param1=param1&param2=param2
I see that it results in
404: "no HTTP-Resource could be found that fits the URI http://localhost:49412/api/vorgang/blubb.
I have tried changing the ajax call to
$.post("../api/vorgang/blubb", JSON.stringify({
param1: "param1",
param2: "param2"
}));
this changes the request text to
{"param1":"param1","param2":"param2"}
but the controller still does not get hit.
I'd be thankful for a hint!
The way you are passing parameter's with HttpPost, I am not sure if it's gonna work. Was going thru FromBody approach mentioned here.
Alternatively, you could try creating a Model object and let the MVC do the heavy lifting.
public class TestController : ApiController
{
[HttpPost]
public void blubb(Parameters param1)
{
// method is not hit, why oh why
}
}
public class Parameters
{
public string param1 { get; set; }
public string param2 { get; set; }
}
Your AJAX call:
var _parameters = {
param1: "param1",
param2: "param2"
};
$.ajax({
type: "POST",
url: "/api/Test/blubb",
cache: false,
data: JSON.stringify(_parameters),
contentType: "application/json; charset=utf-8",
success: function (data) { console.log("Success"); }
});
Final Result :
Not sure, how much will it help!

Receiving Undefined Information from web service

Here is the Code for my WebService,
[WebService(Namespace = "http://mydomain.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class VBRService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string callJson(string x)
{
return "Worked =" + x;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void callJson2(string x, string callback)
{
StringBuilder sb = new StringBuilder();
sb.Append(callback + "(");
var json = new JavaScriptSerializer().Serialize("aString");
sb.Append(json);
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
}
Here is the JavaScript Code,
$.ajax({
crossDomain: true,
contentType: "application/json; charset=utf-8",
url: "http://localhost:31310/VBRService.asmx/callJson2",
data: { x:"someDataPassed", callback:onDataReceived },
dataType: "jsonp",
error: function (data){
alert(data.d);
}
});
function onDataReceived(data) {
alert(data.d);
// ^ Here is where the data comes back as undefined.
}
The JavaScript fires off and hits the onDataReceived function. I'm not really sure as to if this is how you respond from a webService to perform a callback as there are not any examples of server side code to call to.
However, the object data is undefined when it calls back. This is cross domain by the way so that's why I'm trying to figure out how to use jsonp.
Thanks in advance!
This is the correct way to send a jsonp request. You're overcomplicating it.
$.ajax({
url: "http://localhost:31310/VBRService.asmx/callJson2?callback=?",
dataType: "jsonp",
data: {x: "somedata"},
success: function(data){
console.log(data);
}
});
Alternative:
$.getJSON("http://localhost:31310/VBRService.asmx/callJson2?callback=?",{x: "somedata"},function(data){
console.log(data);
});

Categories

Resources