I'm trying to call a server side method from client side via jQuery. My code is as follows:
Server side:
using System.Web.Services; [WebMethod()] //[ScriptMethod()] public static void SendMessage(string subject, string message, string messageId, string pupilId) { //Send message }
Client side:
$("#btnSendMessage").live("click", function(){ var subject = $("#tbSubject").val(); var message = $("#tbMessage").val(); var messageId = $("#hdnMessageId").val(); var pupilId = $("#hdnPupilId").val(); $.ajax({ type: "POST", url: "./MessagePopup.aspx/SendMessage", data: ("subject=" + subject + "&message=" + message + "&messageId=" + messageId + "&pupilId=" + pupilId), error: function(XMLHttpRequest, textStatus, errorThrown){ alert(textStatus); }, success: function(result){ alert("success"); } }); return false; });
I've added a break point on the server side SendMessage method, but it's never hitting it, but when I run the code the jQuery success method is called. What could be causing this?`
No it is not possible to run jQuery on the serverside, as jQuery runs in the users web browser (inside the javascript interpreter) .
Can we call C# code behind using jQuery? we can but we need to specify the backend method as static . Yes,But it having some prerequisiteC# method mark as webmethod.
To call ASP.NET AJAX "ScriptServices" and page methods, you need to use the full $.ajax() syntax:
$.ajax({ type: "POST", url: "MessagePopup.aspx/SendMessage", data: "{subject:'" + subject + "',message:'" + message + ",messageId:'" + messageId + "',pupilId:'" + pupilId +"'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Do something interesting here. } });
See this post for details on why that's necessary: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Edit: The extension doesn't change to .asmx but remains .aspx.
It looks like you're trying to make use of a page method.
Take a look here Page Methods in ASP.NET Ajax for help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With