Web method not getting hit but ajax success says it is - javascript

Update
If I use Fiddler, I see I get a 200 OK Response but the following message:
{"Message":"Authentication
failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
I have no idea where that's coming from.
Original Post
When I place a breakpoint in the web method it is never hit. The success handler runs for the ajax call. If I change the name of the url to incorrect value, I do get an error in F12 tools that it is not found.
I've tried EnablePageMethods='true' as well on the ScriptManager.
JavaScript lives in Scripts folder
$.ajax({
type: 'POST',
url: 'Tasks.aspx/UpdateStatus',
contentType: "application/json; charset=utf-8",
data: '{ id: 8, status: 1 }',
success: function (data) {
alert('it worked!');
},
failure: function (response) {
alert(response.d);
}
});
Tasks.aspx.cs code behind
[WebMethod(EnableSession = true)]
public static string UpdateStatus(int id, int status)
{
TaskManager taskManager = new TaskManager();
taskManager.UpdateStatus((TaskStatuses)status, id);
return string.Empty;
}

I ended up changing PageMethod in the code-behind to a web service asmx file and that seemed to have worked. Now I have to figure out how to secure it.

Related

Problem while using AJAX requesting webmethod info from VB file

I've been trying to call a VB.NET function from JavaScript for the website I've been working on, and found out about AJAX and started trying to use it.
(For reference, my target framework is 4.6.1.)
The following is a snippet of my VB.NET code, where PopulateDetailSection() is something which returns a string which is supposed to be the text from the div, but my breakpoint never hits this function.
System.Web.Services.WebMethod(EnableSession:=True, BufferResponse:=False)
Protected Shared Function PopulateDetail() As HtmlGenericControl
Return PopulateDetailSection()
End Function
and as for the AJAX call:
jQuery.ajax({
url: "frmActiveTrackingG.aspx/PopulateDetail",
type: "GET",
//contentType: "application/json: charset=utf-8",
dataType:"html",
success: function (data) {
alert(data);
}
});
I've tried alerting several things, but it keeps returning undefined unless I alert data which appears to return the aspx file starting with the header.
I usually don't ask questions here, but I'm truly stumped on this.
There some issues with your JavaScript. As described here: https://stackoverflow.com/a/5332290/428010 you need to post on the web page/method.
jQuery.ajax({
url: "frmActiveTrackingG.aspx/PopulateDetail",
type: "POST",
contentType: "application/json: charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
}
});
On the VB side the method need to be public not protected.

Why can't my ajax get request find my handler route when I add arguments?

I am building a web app that displays data about flowers that is stored in my local server running bottle.
My front end is html, js with ajax;
My back end is python with bottle
In the browser there is an empty div in which the data is to be displayed.
Below it there is a row of images. When the user clicks on an image the data should display in the div above.
I tried using $.ajax instead of $.get, and I'm getting the same result.
This is my event listener in js:
$('.image').click((e)=>{
$('.selected').removeClass('selected');
$(e.target).addClass('selected'); // just a visual indication
$.get('/flowerdesc/'+$(e.target).attr('id')).done((data)=>{
flowerInfo = JSON.parse(data);
$('#flower-title').empty();
$('#flower-title').html(flowerInfo.name);
$('.desc-text').empty();
$('.desc-text').html(flowerInfo.description);
})
})
This is my handler for this request:
#get('/flowerdesc/<flower>')
def get_flower_desc(flower):
return json.dumps(data[data.index(filter(lambda f: f.name == flower, data)[0])])
(data is an array of dictionaries, each containing data of a single flower)
I am getting a 404 error (the function get_flower_desc is not executed at all) that possibly is happening because of the argument, because whenever I use a a function with no parameters and pass in no arguments I am getting the result that I'm expecting.
I found that I had to formulate an AJAX request quite precisely to get it to work well with Bottle in a similar scenario.
Here is an example with a GET request. You could attach this function to the event handler or move it directly to the event handler.
function getFlowerData(id) {
$.ajax({
type: "GET",
cache: false,
url: "/flowerdesc/" + id,
dataType: "json", // This is the expected return type of the data from Bottle
success: function(data, status, xhr) {
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
However, I found better results using a POST request from AJAX instead.
function getFlowerData(id) {
$.ajax({
type: "POST",
cache: false,
url: "/flowerdesc",
data: JSON.stringify({
"id": id,
}),
contentType: "application/json",
dataType: "json",
success: function(data, status, xhr){
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
For the POST request, the backend in Bottle should look like this.
#post("/flowerdesc") # Note URL component not needed as it is a POST request
def getFlowerData():
id = request.json["id"]
# You database code using id variable
return your_data # JSON
Make sure your data is valid JSON and that the database code you have is working correctly.
These solutions using AJAX with Bottle worked well for me.

Jquery not passing any parameters data

My Code is as below for Javascript
$.ajax({
type: "POST",
url: "page/rSales.aspx",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
success: function (res) {
alert('Success');
},
error: function (res) {
alert('Fail');
}
});
I use http tracer tools to trace whether or not the parameter is passing on to my backend - and it is not. I have also tried adding contentType: 'application/json; charset=utf-8', adjust parameter by adding colon, but none of it is working.
My Backend code C# :
Request.Params["ListID"].ToString();
It always returns null, due to the parameter not passing on. I am wondering what is causing this problem and how should I resolve it.
The Request.Params collection does not support JSON requests, so you have to parse response body manually (or send it as form data).
https://msdn.microsoft.com/en-us/library/system.web.httprequest.params(v=vs.110).aspx says "Gets a combined collection of QueryString, Form, Cookies, and ServerVariables items."
For firefox you declare var event; before your ajax call this is very well known issue in firefox.

How to call a server side method from JS

I've read many questions, forums, blogs, tried many things and I just can't seems to make it work.
I've tried using PageMethods.MyMethod() and that didn't work. Made sure my ScriptManager had EnablePageMethods ="true" and still nothing. I have a breakpoint on the server side and it never hits. Tried using ajax and still nothing
I'm 1st trying to understand how to make it work to then implemented on my program.
This is what I've tried so far:
Server-side:
[System.Web.Services.WebMethod]
public static void SomeMethod(string subject, string body, string recipients, string CurrentUserId)
{
MessageBox.Show("In c#");
}
JS:
function SomeFuntion()
{
debugger; alert("Before web service");
//PageMethods.CreateDraft(var1, var2, var3, var4);
$.ajax
(
{
type: "POST",
url: "NewMessage.aspx/SomeMethod",
data: "{subject:'" + var1+ "', body:'" + var2+ "', recipients:'" + var3
+ "', CurrentUserId:'" + var4+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function()
{
alert("In ajax");
}
}
);
}
As you can see, I tried PageMethods and it didn't work. I know the function runs cause I see the alert message. By the way, the function is being called when the onclick event is fired of on a button. I don't get any errors and neither does it hit the break point on the MessageBox. This is new to me so any explanation would be very helpful too.
Check for errors from the server:
function SomeFuntion()
{
$.ajax({
type: "POST",
url: "NewMessage.aspx/CreateDraft",
data: "{subject:'" + var1+ "', body:'" + var2+ "', recipients:'" + var3+ "', CurrentUserId:'" + var4+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend:function ()
{
alert("about to send request");
},
success: function()
{
alert("In ajax");
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
);
}
more additions
Since you are telling me that you are getting a "The HTTP verb POST used to access path '...' is not allowed" you might need configuration to enable .NET web service for http POST requests.
I have dropped .NET few years ago and therefore I have no direct experience but from what I could find in other sites you might need configuration at the server level such:
<system.web>
<webServices>
<protocols>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
Or directives above your method such
[ScriptMethod(UseHttpPost = true)]
public string SomeMethod()
{
....
}
I managed to figure it out with the help of a friend, I would post my answer but I believe it's quite long and complicated. I understood most of the things he did but I still didn't believe how it worked. It was pretty much almost the same thing I did but he made the JS in a separate file and set that file like a base JS. Called the web service there and from my JS he called that function that calls the web service. And it worked lol

Ajax do not pass data to method using GET

I have a method which Is accesed using Get
[HttpGet]
[AdminAuthorization]
public ActionResult MakeReservation(ReservationModel m)
{
return PartialView(m);
}
here Ajax Code:
$.ajax({
url: "/DeviceUsage/MakeReservation",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({ data: Ids }),
error: function (data) {
alert("Dodanie nie powiodło się Jeden lub wiecej numerów seryjnych nie są unikalne " + data);
},
success: function (data) {
$('#ProperModal.modal-body').html(data);
$("#Modal").modal('show');
//if (data === "sukces") {
}
});
If I change method description and ajax type to POST function works. How should I modify this code to make it work wiht GET calls?
You need to use JsonRequestBehavior.AllowGet in your controller. For more information you could read this answer on SO
And I think it is good practise to return Json (not PartialView) in your action (for ajax). If you want to return PartialView, you could use this technique
You don't need to explictly tell the HttpGet, By Default, it takes it as HttpGet, but if you put HttpPost attribute, then it does not work on Get Requests.
Same is the case for Jquery ajax, if you don't tell it, its get or post request, it by default makes a get request to server
Remove contentType and dataType: 'json' (this indicates you are returning json, but your code returns a partial view). And Remove JSON.stringify as jQuery accept your JS object directly. Haven't tested it, but it should work.

Categories