citm09 citm09 - 3 months ago 20
Ajax Question

How to send data from JQuery Ajax to ASP.NET page?

I'm using

JQuery Ajax
to send a data from one domain to an
ASP.NET
page that is in another domain. I'm able to get the response back from
ASP.NET
page but I'm not able to send the data from
JQuery Ajax
. Here is my code:

$.ajax({
url: 'http://somewebsite/dbd/leap.aspx',
data: '{ year: "' + $('#txtYear').val() + '"}',
type: 'POST',
async: true,
cache: false,
dataType: 'jsonp',
crossDomain: true,
contentType:"application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});


I can reach
leap.aspx
page. Note
http://somewebsite
is just a placeholder.

leap.aspx
has the following:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="leap.aspx.cs" Inherits="_Default" %>
<%=output %>


leap.aspx.cs
has the following: Note I'm using
Request.Params["year"]
to get the value of year passed by
Ajax
call but no luck.

using System;

public partial class _Default : System.Web.UI.Page
{
public string output = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["callback"] != null)
{
output = Request.Params["callback"] + "('" + GetData(Request.Params["year"]) + "')";
}
}

[System.Web.Services.WebMethod]
public string GetData(string year)
{
return "From outer space! " + year;
}


}

When I run this code, in console I see


"result: From outer space!"


but I do not see the data sent for year by
Ajax
. I'm using
JSONP
because I'm making a cross-domain request to get around Same Origin Policy. I'm not getting any error. I'm just not getting the getting the value of year returned from
ASP.NET
page.

How do I get the year?

Answer

Change the data setting to remove the quotes like this:

data: { year: $('#txtYear').val() },
Comments