InGeek
InGeek

Reputation: 2682

Pass paramater to webservice on ajax

I have a simple web service with one argument :

public static string LoadComboNews(string id)
{
    string strJSON = "";
    DataRowCollection people = Util.SelectData("Select * from News where person = "+ id +" Order by NewsId desc ");
    if (people != null && people.Count > 0)
    {
        //temp = new MyTable[people.Count];
        string[][] jagArray = new string[people.Count][];

        for (int i = 0; i < people.Count; i++)
        {
            jagArray[i] = new string[] { people[i]["NewsID"].ToString(), people[i]["Title"].ToString() };
        }

        JavaScriptSerializer js = new JavaScriptSerializer();
        strJSON = js.Serialize(jagArray);
    }

    return strJSON;
}

on javascript I am trying to call it with parameter :

jQuery.ajax({
        type: "POST",
        url: "webcenter.aspx/LoadComboNews",
        data: "{'id':usrid}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            // Replace the div's content with the page method's return.
            combonews = eval(msg.d);
        }

    });

UPDATE:

usrid is dynamic

Am I doing something wrong here?

Upvotes: 0

Views: 101

Answers (2)

feco
feco

Reputation: 4423

Add WebMethod to the method

[WebMethod]
public static string LoadComboNews(string id)

And try this format

$.ajax({
    type: "POST",
    url: "webcenter.aspx/LoadComboNews",
    data: '{"id":"usrid"}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        // Replace the div's content with the page method's return.
        alert(msg.d);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(textStatus, errorThrown);
        alert(textStatus + " " + errorThrown);
    }
});

Or

data: '{"id":"' + usrid + '"}',

Upvotes: 1

Parv Sharma
Parv Sharma

Reputation: 12705

data you are sending is invalid "{'id':usrid}"

this not a valid json probably what you wanna do is assuming usrid is a variable

"{\"id\":"+usrid+"}"

with it shoudnt you be executing this command

Select * from News where person = '"+ id +"' Order by NewsId desc

Considering id is a string

also try this

combonews = JSON.stringify(msg);

Upvotes: 1

Related Questions