JS:
function showComments(couponId) {
var jsontxt = JSON.stringify({ couponId });
$.ajax({
type: "POST",
url: "<% =Page.ResolveUrl("~/Admin/UserCoupons.aspx/GetComments") %>",
data: jsontxt,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
//async:true,
success: function (result) {
alert("We returned: " + result.d);
},
failure: function (response) {
alert(response.d);
}
});
}
C#:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetComments(string couponId)
{
//will return precomipled generated html for display in div
return "Success";
}
The C# code is in page's code behind .cs file
i have solved this all before using stack over flow
thanks to experts here.
but this time there is some thing else
i am getting my debug pointer in page_load method then in master page's page load method. but debug doesn't enters to the GetComments
and getting exception
Unknown web method GetComments.
Parameter name: methodName
Below is the stackTrace
at System.Web.Script.Services.WebServiceData.GetMethodData(String methodName)
at System.Web.Script.Services.RestHandler.CreateHandler(WebServiceData webServiceData, String methodName)
at System.Web.Script.Services.RestHandler.CreateHandler(HttpContext context)
at System.Web.Script.Services.RestHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)
at System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)
at System.Web.HttpApplication.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Your data in ajax should be JSON.stringify({ couponId:'123' }) //parameter name & value.
function showComments(couponId) {
var jsontxt = JSON.stringify({ couponId:'123' });
$.ajax({
type: "POST",
url: "<% =Page.ResolveUrl("~/Admin/UserCoupons.aspx/GetComments") %>",
data: jsontxt,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
//async:true,
success: function (result) {
alert("We returned: " + result.d);
},
failure: function (response) {
alert(response.d);
}
});
}
after a long google and all others and applying every possible solutions. finally, i found a solution. and that's
edit the file at ~/App_start/RouteConfig.cs
replace
settings.AutoRedirectMode = RedirectMode.Permanent;
with
settings.AutoRedirectMode = RedirectMode.Off;
this solved my problem. any ways thanks to all who took interest and showed their generosity.
Related
This is my aspx page code
function grid(datas)
{
var datass = {datas: datas};
var myJSON = JSON.stringify(datass);
$.ajax({
url: 'EditCustomerBills.aspx/LoadGrid',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: myJSON,
success: function (data) {
alert("Success");
},
error:function(error){
alert("failed");
}
});
}
and this is my behind code
[WebMethod]
public static string LoadGrid(string datas)
{
//GetCustomerBillDetail(data);
string datass = datas.ToString();
return datass;
}
I'm using code perfectly, but output is failed. I'm struggling for four days. please help me. thank you.
I don't know what is your "myJSON" is . according to me your code should be sometinhg like this.
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string datas)
{
return "Hello " + datas + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "CS.aspx/GetCurrentTime",
data: '{datas: "Your Data" }', // your data should be here.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
below picture will give you a idea how we can call the server side method.
for more reference please see this.
edit as follows and share with f12 in console output?
error: function (error) {
console.log(error);
}
This is my api code that return successfull json data while using get method
public Question[] Get() {
getQuestion obj = new AllDataAccess.getQuestion();
return obj.questionList().ToArray();
}
This is my post method data that accept the value and save in database
public void Post([FromBody] string question) {
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
This is the method that call my api
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values',
data: "{'question':'" + $("#submit").value + "'}",
dataType: 'json',
async: false,
success: function(data, status) {
console.log(status);
},
error: function(err) {
console.log(err);
}
});
Now the problem is when i post the data with one textbox value its give me a message in console that "nocontent" and record save in data base with null value
It seems that your ajax url is wrong. You should specify the action name (post). Also, use JSON.stringify to retrieve proper json from javascript object.
var postData = { question:$("#submit").val() };
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values/post',
data: JSON.stringify(postData),
dataType: 'json',
success: function (data,status) {
console.log(status);
},
error: function (err) {
console.log(err);
}
});
In the server side, you should create a model class for Post method;
public class PostInput
{
public string Question { get; set; }
}
And then Post method looks like;
[HttpPost]
public void Post([FromBody]PostInput input)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
If you want to use FromBody, you can do so.
JavaScript
$.ajax({
type: "POST",
//default content-type, could be omitted
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: 'http://localhost:53893/api/values/post',
data: {'': $("#submit").val()}
});
API action
[HttpPost]
public void Post([FromBody]string question)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
You had these issues.
Wrong content-type for your ajax call.
Data was not posted correctly.
val() should be used instead of .value.
API action should be decorated with [HttpPost].
The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}
I have a simple set up.
Jquery:
$.ajax({
url: "/MyApp/MyHandler.ashx/MyMethod",
success: function(result) {
alert("sucess");
},
error: function() {
alert('Error');
}
});
and web method:
[System.Web.Services.WebMethod]
public static void MyMethod(){
new AnotherClass(null).AnotherMethod(null, null);
}
problem is success alert is called but break point is not hit inside MyMethod.
I had the same issue and this is what I ended up having to do:
$.ajax({
url: _url,
data: '',
dataType: 'json',
contentType: 'application/json',
type: 'POST',
success: function(result) {
alert("sucess");
},
error: function() {
alert('Error');
}
});
My first attempt left out the data, dataType and contentType; Only when I set contentType: 'application/json' with an empty string (data: '') did it end up working. What a headache - hope this helps someone else!
In my case, the issue was in RoutingConfig.So, sort that in App_Start folder, within RouteConfig,commented out the following line
//settings.AutoRedirectMode = RedirectMode.Permanent;
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.