-1

Possible Duplicate:
How To Return Value From Code Behind To AJAX?

This is my AJAX code

$.ajax({
        type: 'POST',
        url: 'country_management.aspx/save',
        cache: false,
        data: "{'parameter':'paramValue'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
                 alert(data.d);
                 if (data.d == "error") {
                    $('.success_box').hide();
                    $('.error_box').show();
                 }
                 else {
                    $('#name').val('');
                    $('.error_box').hide();
                    $('.success_box').show();
                 }
        }
});

Code Behind:

[WebMethod]
[ScriptMethod]
public static string save(string parameter)
{
    string name = HttpContext.Current.Request.QueryString["name"].Trim();
    return "error";
}

after writing the first line, return statement does not return anything to the AJAX.

Community
  • 1
  • 1
Chirag Gohel
  • 185
  • 1
  • 3
  • 13

2 Answers2

0

Because you didn't post any field or property "name" If you do the ajax after clicked in a button inside form, data will be the form serialized.

Another thing is, why should you expect "name" var in query string, I don't see any url with aspx?name="any name"

Alberto León
  • 2,879
  • 2
  • 25
  • 24
0

Without knowing the context of the whole application is kind of difficult to answer your question. (Does name get supplied from elsewhere in the app, you could make use of a session?)

But what is stopping you from passing the name through in the ajax call? Rather than just sending through'parameter':'paramValue'.

You have to remember your query string is supposed to contain the parameter you're looking for. at the moment it's looking something like.

http://www.somesite.com/country_management.aspx/save?parameter=paramValue

when you actually need

e.g.

http://www.somesite.com/country_management.aspx/save?parameter=paramValue&name=newName

Javascript

$.ajax({
        type: 'POST',
        url: 'country_management.aspx/save',
        data: { parameter:'paramValue', name: 'newName'},
        success: function (data) { 
           //do something with the response
        }         

});

Codebehind

[WebMethod]
[ScriptMethod]
public static string save(string parameter, string name)
{
    PerformSave(name, parameter);
    return "Data Saved!";
}

TIP

Try out this app. Fiddler. It's extremely useful when you're working with things like ajax calls etc. Actually any web development. :)

Rohan Büchner
  • 5,333
  • 4
  • 62
  • 106