0

When executing an ajax request using jQuery I am not sure how to add a variable to the data that is being sent to the server. Sending a request with a static string works fine:

$("#btnSubmit").click(function () {

                var inputtext = $("#txtInput").val();

                $.ajax({
                    type: "POST",
                    url: "Webform1.aspx/Function",
                    data: "{'ans':'hello'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        alert(msg.d);
                    }

                });
            });

The above calls the .net function and then produces a msgbox with the response string.

How can I replace the hard coded string 'hello' with a variable such as the inputtext variable above.

The following does not work and results in 500 errors that relate to json parsing:

{'ans':inputtext}

{ans:inputtext}

{"ans":inputtext}

(ans is the name of the function parameter)

Edit:

To process the request server side I just use the .net WebMethod attribute for the function, which works with the hard-coded string request in the above example but simply returns the entire html page when passed a variable using data: {ans:inputtext}:

    [System.Web.Services.WebMethod]
    public static string Function(string ans)
    {

        return ans;
    }
broccoli_soup
  • 309
  • 4
  • 14
  • 2
    [`"{'ans':'hello'}"` is not valid JSON!](http://jsonlint.com) Strings and object keys in JSON must be delimited by **double** quotes. jQuery is likely encoding that string as JSON again, which suggests something is wonky in your _server_ code; the client looks fine to me. – Matt Ball Feb 15 '13 at 00:05
  • @MattBall Apparently when json passing data to a webservice function you need to first convert it into a string which why {ans: intputtext} wasn't working for me - http://stackoverflow.com/questions/6323338/jquery-ajax-posting-json-to-webservice – broccoli_soup Feb 15 '13 at 00:59

3 Answers3

2

This should work :

$("#btnSubmit").click(function () {
    var inputtext = $("#txtInput").val();

    $.ajax({
        type: "POST",
        url: "Webform1.aspx/Function",
        data: {ans: inputtext},
        dataType: "json",
        success: function (msg) {
            alert(msg.d);
        }
    });
});

As long as #btnSubmit is'nt an actual submit button in a form.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • @MattBall - I noticed that, but it's still the right way to do it. – adeneo Feb 15 '13 at 00:06
  • @adeneo `alert( msg.d ); // "Right way!"` ? ;) – Roko C. Buljan Feb 15 '13 at 00:12
  • @roXon - who knows what that is, could be a string, the OP does'nt seem to have any issues with that, yet ? – adeneo Feb 15 '13 at 00:14
  • 1
    @adeneo Perhaps this is more of a server-side issue - but your code (which i tried just now) seems to not invoke the function, rather the server simply responds with the entire page, whereas sending the static string {'ans':'hello'} produces the desired result - any ideas? – broccoli_soup Feb 15 '13 at 00:17
  • You're doing something to parse the string that works, on the serverside, that does'nt work with a regular object, which should be converted to a string when sent as a POST request as far as I know. You should post how you retrieve the value on the serverside as well. I guess Matt Ball was right, again! – adeneo Feb 15 '13 at 00:21
  • _"I guess Matt Ball was right, again!"_ I'm Matt Ball, and I approve this message. `:P` – Matt Ball Feb 15 '13 at 03:34
0

The value for your data option looks odd. I usually do it the following way:

 $.ajax({
                    type: "POST",
                    url: "Webform1.aspx/Function",
                    data: {'ans':'hello'},
                    contentType: "application/json; charset=utf-8",

                    success: function (msg) {
                        alert(msg);
                    }

                });

i removed dataType: "json", i think json is the default anyway

Tucker
  • 7,017
  • 9
  • 37
  • 55
0

If you used the submit event instead of button click, then it'll be easier to get a reference to form, then call .serialize on the form, which will include all of the form fields. As long as the [name] attribute of the input is "ans" then it will end up in the json with that name. My example assumes you add "answerForm" class to the form which you want this behavior for.

.on('submit', '.answerFornm', function (e) {
  $.ajax({
  ...
    data: $(this).serialize(),
    contentType: "application/json; charset=utf-8",
  ...
AaronLS
  • 37,329
  • 20
  • 143
  • 202