How to call a server side method from JS - javascript

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

Related

Web method not getting hit but ajax success says it is

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.

Getting 500 Internal Server Error when calling a WebMethod using ajax

I am having an issue hitting my C# WebMethod on the code behind and getting 500 internal server error. I don't really understand why it won't hit it so it would be really great if someone could tell me what is the problem.
So this is my ajax call and doesn't work even with data and datatype not commented out.
$('#chkBxAutoCost')
.click(function(e) {
$.ajax({
type: "POST",
url: "BatchReportCriteriaSelection.aspx/GetAutoJsonBatches",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: "{}",
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Request: " +
XMLHttpRequest.toString() +
"\n\nStatus: " +
textStatus +
"\n\nError: " +
errorThrown);
},
success: function() { console.log("success") }
});
}
);
And this is my code behind method of the page:
[WebMethod]
public string GetAutoJsonBatches()
{
return autoJsonBatches;
}
So I have attached a breakpoint on this WebMethod and it's not being hit. I am pretty stuck so if someone had any insight I'd greatly appreciate it.
So as botond said in the comments my problem was that webmethods need to be static! Thanks very much was really wrecking my head!
First you have edit RouteConfig.cs and use
settings.AutoRedirectMode = RedirectMode.Off;
Next edit your GetAutoJsonBatches() to static
They're static because they are entirely stateless, they don't create an instance of your page's class and nothing is passed to them
in the request (i.e. ViewState and form field values).
HTTP is stateless by default, ASP.Net does a lot of stuff in the
background with ViewState, Session, etc. during a standard page
request to make life easier for developers.
Source
[WebMethod]
public static string GetAutoJsonBatches()
{
return autoJsonBatches;
}
To allow this Web Service to be called from script, using ASP.NET AJAX, you need to use [System.Web.Script.Services.ScriptService] attribute for your WebService.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string GetAutoJsonBatches()
{
return autoJsonBatches;
}
}
And you haven't provided us what exactly is the exception message.

.Next To remove limitation on data send using JSONP

Can we remove the limitation on data send using JSONP. Below is my code. What i am trying to do is to pass 3000 characters(actuallly a image which is converted to base64 data) at a time to service(serviceCall.ashx). As my data is large up to 30,000-40,000 characters i am dividing it in packets(3000 each ) and then sending it. Is there any way i can send this complete data in one go. Reason for switching to JSONP is to avoid the pop up on IE which says 'This page is accessing info that is not.....'. I know as JSONP uses GET method there would obviously a data limitation but is there any way to work around this problem.
$.ajax({
type: "GET",
url: 'http://sys108/restnew1/serviceCall.ashx',
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
async: false,
data: {
datachunk: imgdatachunk,
packetlen: imgdatachunk.length,
imagekey: imageid
},
success: function (data) {},
error: function (jqXHR, textStatus, errorThrown) {
if (window.console)
console.log("Error... " + textStatus + " " + errorThrown);
}
});
No, it's not possible to send a GET request of that length in a more-or-less reliable way: actually, it depends both on how the web server is set up and what client (= browser) is used by someone who works with your application.
So I'd suggest looking for alternative (to JSONP) solutions - like CORS, for example.

Unable to get a simple jQuery.Ajax call to work

I'm pretty new to the web-dev world, and I'm having a bear of a time getting a simple jQuery.ajax call to work. Here is the call:
var url = "http://client.the_url.com/get_account_data.php";
$.ajax({
url: url,
dataType: 'json',
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:function (xhr, ajaxOptions, error){
alert("Error");
}
});
I can copy and paste the url into a browser and it renders what I would expect:
{
"id":"Level 3.xpusdscah",
"type":"Level 3",
"name":"xpusdscah",
"total":0,
"in":0,
"out":0
}
Instead, I get the Error alert every time. :/.
The php script I'm hitting starts with the header:
header('Content-type: application/json');
I was trying to pass params to the php script, but now I'm not even doing that. I would think this should be a 'no brainer', but if it is, then I have no brain. I'm trying to figure out how to use wireshark right now, but should I really need to use wireshark to debug a call that is as simple as it gets to a php file?
Can anyone help me? What I'm really hoping for is a "Well duh, you didn't do (insert obvious solution here)!
Thanks in advance,
Fledgling web developer
First, your callback function isn't helpful. It just shows the text "Error" every time. You want to actually display what the error is, like this:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:error(jqXHR, textStatus, errorThrown){
alert("Error:" + textStatus+ "," + errorThrown);
}
});
Your parameters for the error callback were named strangely. The documentation says the second param is a text error code, and the errorThrown is the HTTP status code provided by the web server. See the documentation here: http://api.jquery.com/jQuery.ajax/
Next, you'll want to grab a packet sniffer. This will allow you to inspect the packets going to and from the web server and see the error message that it is throwing. A good free option is Fiddler.
The data you're sending is not json.
var data = "login="+localLogin+"&pw="+localPassword+"&forAccount="+forAccount+"&forAccountType="+forAccountType+"&topAccount="+topAccount+"&fromDate="+fromDate+"&toDate="+toDate;
Should be something like this:
var data = '{"Key1":"' + Value1 + '","Key2":"' + Value2 .... + '""}';
And perhaps you should add the type as POST and content type like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: ....
try these:
inspect the Network tab on your console.
copy and paste the response and parse it in the console command line to verify the JSON is well formed.
show more verbose error description.

Invalid JSON with markup of my html page

I have created jquery script that was successfully run on my local machine.but when i uploaded the same script on remote server then jquery script generate error. error is "Invalid Json" and XMLHttpRequest.responseText property show my html page markup in. i have spent 3 days on internet to find the solution but i didn't. my code is here:
<script type="text/javascript">
var pageUrl = '<%=ResolveUrl("~/test2.aspx")%>'
$(document).ready(function () {
$('#<%=Button1.ClientID %>').click(function () {
$.ajax({
type: "POST",
url: pageUrl+ "/ServerSideMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("1");
$('#myDiv').text(msg.d);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Failure: " + textStatus + XMLHttpRequest.responseText );
}
})
return false;
});
});
</script>
and my web method is
_
Public Shared Function ServerSideMethod() As String
Return ("Muhammad Aurangzeb")
End Function
The problem comes from the json generated by your "/ServerSideMethod". Check is validity with http://jsonlint.com/ to find the problem.
Often an history of quotes ' versus the good use of "
If your page method is returning the page's HTML, but your local setup is working correctly, your remote server isn't configured correctly.
If it's ASP.NET 3.5, make sure the remote server's web.config matches your local one.
If it's ASP.NET 2.0, you need to also install the ASP.NET AJAX Extensions.
More information: http://encosia.com/2010/03/08/asmx-scriptservice-mistakes-installation-and-configuration/

Categories