I want to post data to server with ajax call but i am getting an error.
var userdata = {};
userdata["Name"] = "Saran";
var DTO = { 'userdata': userdata };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/update",
data: JSON.stringify(DTO),
datatype: "json",
success: function (result) {
//do something
alert("SUCCESS = " + result);
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
console.log("error: " + errorthrown);
}
});//end of $.ajax()
I have created a function in Default.aspx.cs and tried to access that function with the above call.
[WebMethod]
public static string update(string userdata)
{
return "Posted";
}
Error :
POST http://localhost:33762/Default.aspx/update 401 Unauthorized 52ms
Message "Authentication failed." StackTrace null ExceptionType
"System.InvalidOperationException"
Firstly, you have to set/update to settings.AutoRedirectMode = RedirectMode.Off; in App_Start/RouteConfig.cs.
Secondly, your ajax payload is not structured properly to make the appropriate call to the update method. See updates below:
var DTO = { 'userdata': 'Saran' };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/update",
data: JSON.stringify(DTO),
datatype: "json",
success: function (result) {
//do something
alert("SUCCESS = " + result.d);
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
console.log("error: " + errorthrown);
}
});//end of $.ajax()
Related
I am trying to call a webmethod from AJAX which is redirecting to a url like this:
HttpContext.Current.Response.Redirect(StoreCode.ToLower() + "/App/home.html?EventClick=True", false);
AJAX call:
function TokenPost() {
var token = $('#hdnToken').val();
$.ajax({
url: 'http://localhost/QDC/WebServices.asmx/ChkToken',
type: 'POST',
data: "{data:'" + token + "'}",
contentType: 'application/json; charset=UTF-8',
datatype: 'JSON',
success: function(response) {
},
error: function(response) {
alert(response.d);
}
});
}
But my AJAX call is not redirecting to that url.Thanks in advance.
I think it' s not possible in HttpPost Methods. But you can return link in your HttpPost method from server. And redirect with Javascript Code if ajax returns success.
$.ajax({
url: 'http://localhost/QDC/WebServices.asmx/ChkToken',
type: 'POST',
data: "{data:'" + token + "'}",
contentType: 'application/json; charset=UTF-8',
datatype: 'JSON',
success: function (link) {
window.location.href = link;
},
error: function (link) {
alert(response.d);
}
});
In Server Method (I am using this in ASP.NET MVC):
string link = "https://...Your Link";
return Json(link, JsonRequestBehavior.AllowGet);
If you are using WebMethod, I think you can return just string, too.
[System.Web.Services.WebMethod]
public static string ChkToken(string data)
{
string link = "...";
// Do things
return link;
}
This time ajax return can be like this,
success: function (link) {
window.location.href = link.d;
},
I have the following ajax function
var jsonId = JSON.stringify(sortedIDs);
$.ajax({
type: "POST",
data: { ids: jsonId },
datatype: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/Dev/TestSortTable.aspx/GetData",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has occured");
}
});
And the following method in the code behind page
[WebMethod]
public static string GetData(string[] data)
{
return "this is the string from the code behind file";
}
The error I am getting is a 500 internal server error. If I add .cs to the TestSortTable.aspx I get a 404 not found error. This is the first time I have implemented an Ajax function and I am at a loss as to what I have done wrong. I should add that sortedIDs is defined elsewhere.
You're not sending the parameters as JSON. You're converting sortedIDs to JSON, but being wrapped into an object that gets sent as URL-encoded data. You need to do:
var json = JSON.stringify({data: sortedIDs);
$.ajax({
type: "POST",
data: json,
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/Dev/TestSortTable.aspx/GetData",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has occured");
}
});
Also, datatype: should be dataType:
My AJAX code is below. In this i cannot get the response from server side C# code. But there is no issues with my server side code ( I have checked it by debugging ). From server side i am returning string to this ajax.
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]' +"provider/GetState",
contentType: 'application/json',
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
}
});
Server side code is below
public string GetState(string CountryId)
{
int i= Convert.ToInt32(CountryId);
var Details = objUserAccount.SP_Getstate(i).ToList();
if(Details.Count>0)
{
return "Success";
}
else
{
return "False";
}
}
Add datatype in your ajax request like this, if datatype is not matched with received data from server then the ajax error will call instead of success
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]'+ NSSCTProvider/GetState",
contentType: 'application/json',
dataType: "json",
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
},
error: function(data){
alert("Error occured");
}
});
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]'+ NSSCTProvider/GetState",
contentType: 'application/json',
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
},
error: function(data){
alert("Error occured");
}
});
Either one of the success or failure call back will be initiated if the request is made from this snippet. Might be a server issue, most probably. And make sure that this is the code snippet getting executed. Happens to me all the time.
GetData(...) method was OK, but SetSimple(...) method throwing error 400.
Javascript:
$.ajax(url,
{
type: action,
timeout: 3000,
data: { value: 123 },
contentType: "application/json; charset=utf-8",
//dataType: "json",
success: function (data, textStatus, jqXHR) {
displayInfo("success: "+data);
},
error: function(jqXHR, textStatus, errorThrown ) {
displayInfo("error: "+errorThrown+" "+textStatus);
}
}
);
C#:
[WebGet(RequestFormat = WebMessageFormat.Json)]
string GetData(int value);
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")]
string SetSimple(int value);
To run/test it I have the service opened in a browser, then my test page with the javascript in another browser. (And dataType: "json" doesn't seem to help.)
And the fiddler response shows "The server encountered an error processing the request. See server logs for more details", but I don't see anything in the Event Logs. Anyone see if/what I'm doing wrong?
You should be transform your JavaScript object into string.
JSON.stringify(data)
Then on your example
$.ajax (url,
{
type: action,
timeout: 3000,
data: JSON.stringify({ value: 123 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
displayInfo("success: "+data);
},
error: function(jqXHR, textStatus, errorThrown ) {
displayInfo("error: "+errorThrown+" "+textStatus);
}
}
);
Your ajax request is setting the "data" property to { value: 123 }. You need to pass the appropriate object to the SetObject method which is CompositeType. The ajax request looks like you're using it as a utility function so just pass data as a parameter so the ajax request would be:
var makeAjaxCall = function(url, action, data) {
$.ajax(url,
{
type: action,
timeout: 3000,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
displayInfo("success: "+data);
},
error: function(jqXHR, textStatus, errorThrown ) {
displayInfo("error: "+errorThrown+" "+textStatus);
}
}
);
}
I am using ASP.Net and jquery/ajax
I have the following script in jquery:
var sizes = [];
sizes.push({ key: "1", value: "3"});
$.ajax({
type: "POST",
url: pageUrl,
data: '{"sizeList":' + sizes + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
}
This is the codebehind:
public static void AddProductToDB(Dictionary<String, String> sizeList)
Can someone please tell me what I am doing wrong as I have tried everything I could think of.
Thanks
var param = {
'[0].Key': '1',
'[0].Value': '3'
};
$.ajax({
type: "POST",
url: pageUrl,
data: param
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
}
I am looking at this two years after it got posted but hopefully it will help someone if they stumble upon this post. I used the base of Damith's answer to form the parametes I was going to pass and got it to work by passing them the following way:
var param = {
'filters[0].Key': '1',
'filters[0].Value': 'test',
'filters[1].Key': '2',
'filters[1].Value': 'test',
id: 1,
width: 150,
height: 150,
};
Then on the MVC code I had my method with the following signature:
public async Task<ActionResult> IndexPartial(int id = -1, int? width = null, int? height = null, Dictionary<string, string> filters = null)
With these two things I was able to have the method detect the information passed as a Dictionary<string,string> and at the same time I was able to pass in additional parameters. Hopefully this will resolve your issue.
Looks like you are trying to use a page method. If so, you need to decorate your method (in code behind) with the WebMethod attribute
[WebMethod]
public static void AddProductToDb(Dictionary <string, string> sizelist){}
Then make sure you are posting the json object with jquery to the correct url...for example...PageName.aspx/AddProductToDb
That's all you need if you are using page methods
I believe you need to set traditional to true so it will serialize properly
$.ajax({
type: "POST",
url: pageUrl,
traditional: true,
data: '{"sizeList":' + sizes + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
}
Please refer below code. Make sure your method "AddProductToDB" has HttpPost attribute and identical/same name of the parameter in this case "sizeList".
C# / MVC / Back End Side :
[HttpPost]
public static void AddProductToDB(Dictionary<String, String> sizeList)
{
//Business logic or Data
}
Javascript / jQuery / Client Side:
And Enter the URL where you this function/method AddProductToDB.
For example "YourController/AddProductToDB".
<script type="text/javascript">
var sizes = [];
sizes.push({ "Key": "key1", "Value": "value1" });
sizes.push({ "Key": "key2", "Value": "value2" });
sizes.push({ "Key": "key3", "Value": "value3" });
$.ajax({
type: "POST",
url: '/YourController/AddProductToDB',
data: JSON.stringify({
sizeList: sizes
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
</script>
you can use this:
var param = {
'1': '3'
};
$.ajax({
type: "POST",
url: pageUrl,
data: JSON.stringify({sizeList: param}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus);
}
}
then you can read it from dictionary variable with this:
public static void AddProductToDB(Dictionary<String, String> sizeList) {
sizeList["1"]; // return "3"
}