Farzaneh Talebi
Farzaneh Talebi

Reputation: 925

Jquery - Try to send data to Ajax but data is null

There is function that get name from database using Jquery Ajax. This function have input parameter that I get it with below code:

var value = $(this).parent().find(":checkbox").val();
var typeSelect = GetLayerGeometries(value);

Then send value to ajax function:

Ajax Function:

function GetLayerGeometries(LayerName) {
    var data;
    $.ajax({
        url: 'GetLayerGeometries.aspx/GetLayerGeometry',
        data: '{"LayerName":"' + LayerName + '"}',
        async: false,
        success: function (resp) {
            data = resp;
            callback.call(data);
        },
        error: function () { }
    });
    return data;
}

C# Function:

protected void Page_Load(object sender, EventArgs e)
{
    string test = Request.Form["LayerName"];
    GetLayerGeometry(Request.Form["LayerName"]);
}

public void GetLayerGeometry(string LayerName)
{
    WebReference.MyWebService map = new WebReference.MyWebService();
    string Name = map.GetLayerGeometries(LayerName);

    if (Name != null)
        Response.Write(Name);            
}

My problem: LayerName is null.

I use this link and test all ways,but LayerName still is null.

Upvotes: 0

Views: 519

Answers (3)

ManishKumar
ManishKumar

Reputation: 1554

You need to stringify value and then send it, it will work

function GetLayerGeometries(LayerName) {
    var data;
    $.ajax({
        url: 'GetLayerGeometries.aspx/GetLayerGeometry',
        data: { LayerName: JSON.stringify(LayerName) }, // make this change
        async: false,
        success: function (resp) {
            data = resp;
            callback.call(data);
        },
        error: function () { }
    });
    return data;
}

Upvotes: 0

abagshaw
abagshaw

Reputation: 6592

The problem is, you are trying to parse the request body as if it was form encoded, which it is not. You've passed the data using JSON so you need to parse it appropriately.

Use the following in your C# to read the request variables from JSON using Json.NET:

protected void Page_Load(object sender, EventArgs e)
{
    string requestBody = StreamReader(Request.InputStream).ReadToEnd();
    dynamic parsedBody = JsonConvert.DeserializeObject(requestBody);
    string test = parsedBody.LayerName;
}

Upvotes: 0

Neeraj Pathak
Neeraj Pathak

Reputation: 759

function GetLayerGeometries(LayerName) {
    var data;
    $.ajax({
        url: 'GetLayerGeometries.aspx/GetLayerGeometry',
        data: {"LayerName":LayerName},
        async: false,
        success: function (resp) {
            data = resp.d;
            callback.call(data);
        },
        error: function () { }
    });
    return data;
}

[WebMethod]
public static string GetLayerGeometry(string LayerName)
{
    return LayerName
}

you need to use web Method just like above method.

Upvotes: 1

Related Questions