I am trying post a string to web service but I am getting this error (Google Chrome Extension Project):
jquery-2.1.1.min.js:4 POST http://localhost:49242/Service.asmx/test
500 (Internal Server Error)
Here is my ajax code:
var data = {};
data.param1 = words[0];
$.ajax({
data: JSON.stringify({ 'data': data.param1 }),
dataType: 'application/json',
url: 'http://localhost:49242/Service.asmx/test',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
My service:
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string test(string param1) {
return param1;
}
I am working on this problem about 3 days. Can you help me ?
By the way, I have a question. I am posting json variable to service with ajax(like you see), but service returning xml value. Is there a problem or [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] this code block solving problem?
Your error come from your data parameter. Stringify data object instead of { 'data': data.param1 } :
var data = {};
data.param1 = words[0];
$.ajax({
data: JSON.stringify(data),
dataType: 'application/json',
url: 'http://localhost:49242/Service.asmx/test',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
Your stringifyed data will result in {"param1":"Words"}, then your service should be able to bind the param1 parameter.
I was facing this type of error on AJAX post response. I was spending too much time behind this issue and finally I caught it.
It throws a 500 internal error because the AJAX response has a lot of content from the server so it returns a timeout of execution.
So I just added the line below and it's working fine.
Page.Server.ScriptTimeout = 300;
Related
and thank you in advance for helping me.
I'm trying to make a POST where I pass the TOKEN in the URL and I want to pass another param too so I can save the info in the DB. I have this:
$("#btnAddCompany").click(function(e) {
var token = "123";
var companyValue = document.getElementById("companyValue").value;
var obj ={CompanyId: 4 ,Name: companyValue }
var postData = JSON.stringify(obj);
console.log(postData);
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
contentType: "application/json",
data: postData,
url: "http://banametric.ddns.net/BanaMetricWebServices/BanaSov_WS.svc/CompanySave/"+token,
success: function(data) {
toastr.success("Lidl Adicionado!");
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
But I'm getting an 400 error (Bad Request) so I assume that I'm making something wrong, but I don't find out what. The error trace is this:
AJAX error in request: { "readyState": 4, "responseText": "\r\n
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 server logs for more
details. The exception stack trace is: \r\n at
System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
message, Object[] parameters)\r\n at
It's error because of
The expected message formats for the operation are 'Xml', 'Json'.
So you can pass contentType in your ajax call
$.ajax({
....,
contentType: "application/json"
})
I am not sure, but it depends on what server wants to read from you.
Server does not want to read raw bytes, it wants xml or json
Try to add headers like
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
in $.ajax() function
You need to set the content type header in your request to inform the server you're sending the data as JSON.
The error message is telling you that the server does not understand the content you're sending it - you have to give it a hint that the data is in a particular format, especially because, again as mentioned in the error message, it allows you to submit in more than one different format (JSON or XML in this case).
Adding
contentType: "application/json"
to the options in your $.ajax call should resolve the issue.
P.S. We can't see the signature of your controller method but it's possible you may also need to give your parameter a name within the JSON, e.g. something like data: JSON.stringify({ "companyValue": postData }); , but there's not enough info in your question to say for certain what the correct structure should be.
$("body").on("submit", ".example_form", function() {
$.ajax({
url: 'http://example.com/{ROUTE_URL}',
data: new FormData(this),
processData: false,
contentType: false,
/* OR contentType: "application/json; charset=utf-8"*/
type: 'POST',
dataType: "json",
success: function(data) {
console.log(data);
}
});
});
Instead of this
var postData = JSON.stringify(companyValue);
why don't you try this:
var obj ={token :token ,companyValue:companyValue }
And then make use of the json stringify function
var postData = JSON.stringify(obj);
After that in ajax call only change the url:
url: "http://webservice/CompanySave/"
I keep getting a 405 error upon a POST method
$.ajax({
url: mistergoUrl,
type: "POST",
dataType: "json",
data: body,
crossDomain: true,
contentType: "application/json",
success: function () {
// TODO: find a cleaner way to get the last route
$.getJSON(mistergoUrl)
.done(function (data) {
data = resolveReferences(data);
window.location.replace("Route.html?id=" + data.last().RouteId);
});
},
error: function (httpObj, result) {
Console.log(result);
Console.log(httpObj);
}
});
On the server, the request is valid, is processed and returned as expected, but the Ajax function keeps giving back a 405 error...
This is the asp.net code
[HttpPost]
public IHttpActionResult Post(RoutePostModel postdata)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
_routeService.Add(postdata);
var route = _routeService.GetAll().Last();
var url = Url.Route("DefaultApi", new {controller = "Routes", id = route.RouteId});
return Created(url, route);
}
Does anybody know why and how this could happen? any help is appreciated!
How to send json string via ajax and convert json string to xml?
Error: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
$.ajax({
async: true,
url: "WebForm1.aspx/btnSave",
type: "POST",
data: "{data: '" + "{'?xml': {'#version': '1.0'},'Card': { 'Main_Client_Information': {'Surname': '','Name': '','Middle_name': '','Full_name': '','Short_name': '','RNN': '','IIN': '','Birthday': '','Doc_Type': {'#code': ''}}}}" + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert(response.d);
},
error: function (error) {
debugger;
alert(error);
}
});
if send $.ajax data: '{data: "something"} - work perfect, how to put "json like string" instead "something"
WebForm.aspx.cs
[System.Web.Services.WebMethod]
public static string btnSave(string data)
{
string response = "";
try
{
XmlDocument xmlDocument = (XmlDocument)JsonConvert.DeserializeXmlNode(data);
xmlDocument.Save(Server.MapPath("output.xml"));
response = "success";
}
catch (Exception ex)
{
response = "error" + ex.Message;
}
return response;
}
I just want get this string ---------> "{'?xml': {'#version': '1.0'},'Card': { 'Main_Client_Information': {'Surname': '','Name': '','Middle_name': '','Full_name': '','Short_name': '','RNN': '','IIN': '','Birthday': '','Doc_Type': {'#code': ''}}}}" + "'}" ------------ in webmethod btnSave and convert it to xml format
the problem lies in the way you are telling jQuery which data to post :
You probably got confused, since the parameter passed on to $.ajax has a property named data.
You are now passing a string right into there, while you should be passing a Json dictionary which contains which variable names and values you want to send.
try this :
Your entire call should look something like this :
(i'm keeping the data you are trying to send in a separate variable for clarity)
var stringData ="{'?xml' : '#version': '1.0'},'Card': { 'Main_Client_Information': {'Surname': '','Name': '','Middle_name': '','Full_name': '','Short_name': '','RNN': '','IIN': '','Birthday': '','Doc_Type': {'#code': ''}}}}";
$.ajax({
async: true,
url: "WebForm1.aspx/btnSave",
type: "POST",
data: {data:stringData},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert(response.d);
},
error: function (error) {
debugger;
alert(error);
}
});
You can't send the data as the json string. You need to call JSON.parse (json_string_here_).
It is also possie that you might need put instead of post, but i cant be sure of that because i dont know if you are doing an insert or update.
Sorry, even after that ive got to say that id be a little more than impressed if you can send an xml file like that. I would imagine that doesnt work very well.
I'm sending from view using jQuery to MVC post action
function DoSomething(passedId) {
$.ajax({
method: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
//
});
}
And inside MyController
[HttpPost]
public ActionResult SomeAction(int id)
{
...
}
In Firebug console I'm getting 404 error.
You didn't said which version of jquery you are using. Please check jquery version and in case that this version is < 1.9.0 you should instead of
method: "POST"
use
type: "POST"
this is an alias for method, and according to jquery official documentation you should use type if you're using versions of jQuery prior to 1.9.0.
function DoSomething(passedId) {
$.ajax({
type: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
...
});
}
Tested above code and it works (each request enter inside mvc controller http post SomeAction action).
In the RFC 2616 the code 404 indicates that the server has not found anything matching the Request-URI.
So you need to look at your URL parameter.
Try the MVC conventional call using :
url: '#Url.Action("SomeAction", "MyController")',
To resolve the 404 issue:
There are a few options to resolve this. You controller/action cannot be find the way it is describe.
-If you are in a view that is in the controller for which the action your are trying to call is located, then:
url: 'SomeAction',
-If you are trying to call an action from another controller, OtherController, for example, then:
url: 'Other/SomeAction',
-To add to another answer, if you are calling your ajax inside the view (and NOT in a javascript file) then you can also use (for a controller called SomeController):
url: '#Url.Action("SomeAction", "Some")',
Additional Items Of Note:
You do not specify a content type for json (contentType indicates what you are sending):
contentType: "application/json; charset=utf-8",
I can't tell, based on your action if you are expecting 'text' or something else. However, unless expecting 'json', I would remove the data part.
You need to stringify your data
JSON.stringify(data: { id: passedId}),
In the end, I would expect it to look something like:
function DoSomething(passedId) {
var url = "SomeAction"; //if action is in OtherController then: "Other/SomeAction"
$.ajax({
method: "POST",
url: url,
data: JSON.stringify({ id: passedId}),
contentType: "application/json; charset=utf-8"
}).done(function (data) {
//
});
}
The slash at the beginning of this designates an absolute path, not a relative one.
/MyController/SomeAction/
You should include a URL or relative path.. maybe
'MyController/SomeAction/ajax.php'
or the full URL
'http://example.com/myajaxcontroller/someaction/ajax.php'
or stolen from the other guys answer
url: '#Url.Action("SomeAction", "MyController")',
To address others on here, I don't think the datatype is the
problem... OP says "I'm getting 404 error."
contentType is the type of data you're sending, so
application/json; charset=utf-8 is a common one, as is
application/x-www-form-urlencoded; charset=UTF-8, which is the
default.
dataType is what you're expecting back from the server: json, html,
text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Write the code this way:
function DoSomething(passedId) {
$.ajax({
url: 'yourController/SomeAction',
type: 'POST',
data: { id: passedId},
dataType: 'json',
error: function (ex) {alert(ex.responseText)},
success: function (data)
{
if (data.Results != null) {
//use the return values
});
}
}
});
}
and the controller
public JsonResult SomeAction(int id)
{
try
{
return Json(new { Results = "Text To return or send some object or an list, etc"}, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
Finally, check that the controller has its respective view. :)
and and the library of "jQuery" updated.
just in case.
use the following ajax call
var datum = { id: passedId };
$.ajax({
url: url, // your url
type: 'POST',
data: JSON.stringify(datum),
contentType: 'application/json; charset=utf-8',
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
UpDated
public ActionResult SomeAction(int id){} should accept string parameter instead of int
Hello everyone and thanks for your time.
Here is my javascript:
$('.sender').click(function (e) {
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: { firstName: 'stack', lastName: 'overflow' },
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: function (response) {
alert('success');
},
error: function (response) {
alert('error: ' + response);
console.log('err: '+response);
}
});
});
And here is the code in my .ashx handler:
public void ProcessRequest(HttpContext context)
{
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//to fix the allow origin problem
context.Response.ContentType = "text/plain";
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
While the click event is working, my Ajaxrequest doesn't seem to get any response as the alert at success doesn't popup. I've debugged using the browser's network console and it return the expected response but it doesn't seem to reach the success function in the JavaScript code. Any insights or suggestions are welcome. Thanks.
In case you are still interested in the answer, try this before doing the request
var data = { firstName: 'stack', lastName: 'overflow' };
var jsonData = JSON.stringify(data);
and change your AJAX request to
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: jsonData,
dataType: 'json',
contentType: 'application/json; charset-utf-8'
})
.done(function (response) {
// do something nice
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("request error");
console.log(textStatus);
console.log(errorThrown);
});
Explanation
You are trying to send the plain data object. You must transform it into a Json string using JSON.stringify(object).
Changing the dataType isn't really a solution but a workaround.
Additional Notes
Also, I think you should use .done() and .fail(). See here for further details.