10

html

<a onclick="testGetParametersDynamic2();">fill in names and check it out</a>
<br />
<p>Enter First Name</p>
<input id="myFirstName" type="text" />
<br />
<p>Enter Last Name</p>
<input id="myLastName" type="text" />
<div id="outputGET3"></div>

c#

[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true)]
public string testGetParametersDynamic(string firstName, string lastName)
{
    string fullName = firstName + lastName;

    return fullName;
}

I have tried multiple ways of entering data bc I think this is where the problem lies

attempt 1

function testGetParametersDynamic2()
    {
        $.ajax(
        {
            post: 'GET',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: '{"firstName":"' + $('#myFirstName').val() + '","lastName":' +
                    $('#myLastName').val() + '"}',
            url: 'UtilitieService.asmx/TestGetParametersDynamic',
            success: function (result)
            {
                var test = result.d;
                var outputDiv = $('outputGET3');
                outputDiv.html(test);
            },

            error: function ()
            {
                alert('Fail Test Get Dynamic');
            }
        });
    }

attempt 2:

function testGetParametersDynamic2()
    {
        $.ajax(
        {
            post: 'GET',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: "firstName" + $('myFirstName').val() + "&lastName" + $('myLastName').val(),
            url: 'UtilitieService.asmx/TestGetParametersDynamic',
            success: function (result)
            {
                var test = result.d;
                var outputDiv = $('outputGET3');
                outputDiv.html(test);
            },

            error: function ()
            {
                alert('Fail Test Get Dynamic');
            }
        });
    }

both times I get this error:

Invalid web service call, missing value for parameter: \u0027firstName\u0027

dan_vitch
  • 4,477
  • 12
  • 46
  • 69

3 Answers3

14

I hope that you use [ScriptMethod(ResponseFormat=ResponseFormat.Json)] attribute for the web method or set the same information in the web.config in case of the usage .NET 4.0.

It seems to me that your first attempt was almost correct, but you should replace

data: '{"firstName":"' + $('#myFirstName').val() + '","lastName":' +
                    $('#myLastName').val() + '"}',

to the

data: '{"firstName":"' + $('#myFirstName').val() + '","lastName":"' +
                    $('#myLastName').val() + '"}',

(the starting double-quote was skipped before the $('#myLastName').val()).

I strictly recommend you don't use manual serialization to JSON. For example if the text from $('#myFirstName').val() or $('#myLastName').val() will have '"' or '\' characters, that the characters must be escaped with additional backslash ('\') (see here). Instead of manual serialization you should use JSON.stringify function from the script json2.js which you can download from the http://www.json.org/js.html or here. In recent web browsers the function are native implemented and json2.js use the native implementation if it take place.

The data parameter of $.ajax could be rewritten as the following:

data: {
    firstName: JSON.stringify($('myFirstName').val()),
    lastName: JSON.stringify($('myLastName').val())
}

or in some situation even as

data: {
    firstName: function() { return JSON.stringify($('myFirstName').val()); },
    lastName: function() { return JSON.stringify($('myLastName').val()); }
}

For more information see this old answer and probably also this.

UPDATED: Sorry the correct version without the usage JSON.stringify could be without the data usage:

url: 'UtilitieService.asmx/TestGetParametersDynamic?firstName=' +
     encodeURIComponent('"' + $('#myFirstName').val() + '"') +
     '&lastName=' + encodeURIComponent('"' + $('#myLastName').val() + '"')

I strictly recommend you to use always only the JSON.stringify version which I described above.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • updated the code using your code with addition double-quote. Still getting same error. This is the statement from firebug ?{"firstName":"dan","lastName":"mark"}. Is that right format? – dan_vitch Feb 19 '11 at 01:27
  • @dan_vitch: Why you don't use the version with `JSON.stringify`? You will has correct results in the case. – Oleg Feb 19 '11 at 08:39
2
  • Your first attempt is passing the paramaters as a json string.
  • Your second attempt is missing = signs.

You can pass a object to data, and jQuery will serialize it properly.

$.ajax(
        {
            post: 'GET',
            data: {
                firstName: $('myFirstName').val(),
                lastName: $('myLastName').val()
            },
...
The Scrum Meister
  • 29,681
  • 8
  • 66
  • 64
  • 1
    Note: Avoid making the call as `GET`. Use `POST` instead. See http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx – The Scrum Meister Feb 19 '11 at 00:53
  • 1
    Also, `post: 'GET'` - i think you are looking for the `type` option instead of the `post`(?) option. – The Scrum Meister Feb 19 '11 at 00:55
  • @Scrum I updated code and received this error: Invalid JSON primitive: dan. dan was the name I used in firstName field. – dan_vitch Feb 19 '11 at 01:12
0

Pass multiple parameters using json

data: "{'RecomendeeName':'" + document.getElementById('txtSearch').value + 
                       "'," + "'tempdata':'" +"myvalue" + "'}",
Java Devil
  • 10,629
  • 7
  • 33
  • 48