Reputation: 125
I am trying to do a very simple task. Not sure what I am doing wrong. I need to pass some values to code behind method, do some calculations there and then return the result. I started with a test method. There are many examples on web. But nothing working for me.
Please see my default page code below:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication7._Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
var loc = window.location.href;
$("#btnClick").click(function (event) {
$.ajax({
type: 'POST',
url: loc + "/GetMessage",
data: "{}",
contentType: "application/json; charset=utf-8"
})
.success(function (response) {
alert(response.d);
})
.error(function (response) {
alert(response.d);
});
});
});
</script>
<input id="btnClick" type="button" value="button" />
</asp:Content>
The jquery has been referenced in master page:
<script src="Scripts/jquery-2.1.0.js"></script>
<script src="Scripts/jquery-2.1.0.min.js"></script>
codebehind:
[WebMethod]
public static string GetMessage()
{
return "test";
}
I do get "Undefined" error. When I change the .success and .error function like below
.success(function () {
alert("S");
})
.error(function () {
alert("E");
});
It shows "S". My understanding is that it finds the code behind method. But the 'response' is undefined. Does it mean the code behind method is not returning the data in json format?
Upvotes: 1
Views: 7698
Reputation: 125
I have finally resolved the issue by commenting out the code in App_Start. Murali's suggestion help me to find out the actual issue. The exception was 'authentication failed'. //settings.AutoRedirectMode = RedirectMode.Permanent;
Upvotes: 1
Reputation: 1362
You´ll need to remove the attribute runat="server" in the following line:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
Because that says, that the javascript code runs at the server and not at the client/browser, as excepted. Changing this should fix all your problems.
Upvotes: 0
Reputation: 22619
Try removing .d
and check with console
.success(function (response) {
console.log(response); // in firefox/chrome
alert(response);
})
Check the firebug console for the JSON output. Below is sample screenshot
Upvotes: 0
Reputation: 40639
First use only a single version(minified or unminified
) of jquery
and use dataType:'json'
like,
$("#btnClick").click(function (event) {
$.ajax({
type: 'POST',
url: loc + "/GetMessage",
dataType: 'json', // for json data, which is parsed
success:function (response) {//combining success and error callback in ajax
console.log(response);
},
error:function (response) {
console.log(response);
}
});
});
Upvotes: 0