how can i use ajax to call a server side method i tried this code but it gives me the alert error messsage and i can't find my problem please help and thank you :
enter code here
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ImageEditor_UserControl.ascx.cs" Inherits="ImageEditor_UserControl" %>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type ="text/javascript">
$(document).ready(function () {
$('#<%=uploadButton.ClientID %>').click(function () {
$.ajax({
type: "POST",
url: "ImageEditor_UserControl.ascx/helo",
data: "{}",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function () { alert("success"); },
error: function () { alert("error"); }
})
return false;
});
});
</script>
<asp:Button ID="uploadButton" runat="server" Text="Upload" />
C# Code
[WebMethod]
public static string helo() {
return "Message from server.";
}
You should call *.asmx
files (there are other options but this is for the beginning).
Look out for tutorials on web services & ajax consuming.
Have you checked on the line $('#<%=uploadButton.ClientID %>').click(function () {
that the <%=uploadButton.ClientID %>
is actually replace by the value and not taken literally?
Unfortunately you cannot call a page method (server side method) that is a part of a user control. You will have to use a method in an aspx page.
Do you use firefox? if yes, install the addon "FireBug". Enable firebug to check the request and the response.
Firebug will show you sometimes the error message returned from the server, as in you jquery syntax you are not loading the attributes for the method anonymous method callback for error.
error: function (req,error) { alert("error: " + req.statusText); }
This will give you a heads up on what is going wrong.