Posted by: Nishant Rana | October 22, 2007

Calling Asp.NET web service from javascript (Ajax)-(Passing Parameter-POST)

Hi,

Now we will modify the application that we developed in the previous post to work with POST parameter

http://nishantrana.wordpress.com/2007/10/22/calling-aspnet-web-service-from-javascript-ajax-passing-parameter/

We have changed the get to post as we are now not passing the value for Name by appending it in the url.

Only make changes to the function getMessage()

function getMessage()

{

var name=’Nishant’;

xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);

xmlHttp.open(”POST“, “http://localhost/WebService1/Service1.asmx/HelloWorld”, true);

xmlHttp.onreadystatechange=doUpdate;

xmlHttp.setRequestHeader(”Content-Type”,”application/x-www-form-urlencoded”);

xmlHttp.send(”name=”+escape(name));

return false;

}

Let’s understand the changes that we have made

First of all we have change the method of passing data to POST from GET.

But still we need to pass the name’s value which our web service method needs.

For that we’ll modify our Send() method

xmlHttp.send(”name=”+escape(name));

We are using the same name/value pair in send()  which we used at the end of the request URL in the GET version

escape()-It makes sure that the values are valid values i.e. no tricky characters are there.

But this is not enough that is why we added this line

xmlHttp.setRequestHeader(”Content-Type”,”application/x-www-form-urlencoded”);

Here the server doesn’t know what kind of data it can expect or is coming from our application.

We are making use of setRequestHeader function to tell the server about the content type we are going to send.

The server can get this information from request’s header that it recieves.

Content-Type  -> Name of the header

application/x-www-form-urlencoded -> http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1

Bye

Responses

[...] You can read the rest of this blog post by going to the original source, here [...]

It works fine when only one parameter is to be passed. But could you guide how to pass multiple parameters, when the parameter value contains a ‘&’?

Reply awaited.
Thanks.

Hi Monali,
Say we have to send two parameters fName and lName so in that case we
will have request.send in the following format

request.send( “fName=”+escape(fName) +
“&lName=”+escape(lName) );

I hope this helps you

This was just what I was searching for. Thanks for the post! Can you tell me why you would choose to use the POST rather than the GET option?

Thanks Holly!!

There is a good explanation given over here for Post vs Get
http://weblogs.asp.net/mschwarz/archive/2006/12/04/post-vs-get.aspx

Leave a response

Your response:

Categories