Geeks With Blogs
Jeroen Bourdeaud'hui web application developer

If you want to consume a webservice, it's not allways necessary to do a postback.
It's even not that hard!

1. Webservice

You have to add the scriptservice attribute to the webservice.

public class PersonsInCompany : System.Web.Services.WebService {

Create a WebMethod

public Person GetPersonByFirstName(string name)
List<Person> personSelect = persons.Where(p => p.FirstName.ToLower().StartsWith(name.ToLower())).ToList();
if (personSelect.Count > 0)
return personSelect.First();
return null;

2. webpage

Add reference to your service to your scriptmanager

  <asp:scriptmanager id="ScriptManager1" runat="server">
<asp:servicereference path="~/PersonsInCompany.asmx">

Add some javascript, where you first call your webservice.
Classname.Webmethod = PersonsInCompany.GetPersonByFirstName
Add a callback to catch the result from the webservice. And use the result to update your page.

<script type="text/javascript">
function GetPersonInCompany() {
var val = document.getElementById("MainContent_TextBoxPersonName");
PersonsInCompany.GetPersonByFirstName(val.value, FinishCallback);

function FinishCallback(result) {
document.getElementById("MainContent_LabelFirstName").innerHTML = result.FirstName;
document.getElementById("MainContent_LabelName").innerHTML = result.Name;
document.getElementById("MainContent_LabelAge").innerHTML = result.Age;
document.getElementById("MainContent_LabelCompany").innerHTML = result.Company;

If you have any question, feel free to contact me!

You can download the code here.

Posted on Saturday, January 29, 2011 8:35 AM , javascript , ajax , webservice | Back to top

Comments on this post: Calling a webservice via Javascript

# re: Calling a webservice via Javascript
Requesting Gravatar...
In the first place, I don't know what is the importance of caching. Is this the same with storing? I am not quite sure though. - Joe Zanotti
Left by Joe Zanotti on Jan 24, 2012 5:46 AM

# re: Calling a webservice via Javascript
Requesting Gravatar...
i'm trying to call a web service from java script code stored NOT in Html but in an extenarl file .js. My code is this:

service.useService("http://localhost:10000/WebS_cod_01/WebS_codEurService.asmx?wsdl", "WebS");

Photo = service.WebS.callService("webS_codEurProcessWS" , photoID);

checking with Firebug i find this message:

"service is not defined"

where i'm wrong ?

thanks in advance
Left by giocot on Feb 17, 2012 6:27 PM

# re: Calling a webservice via Javascript
Requesting Gravatar...
I don´t really know what you are doing wrong. It´s just like you´re not doing the same as I'm doing :) But the link to the download is corrupt. I've fixed it.

And if you can't fix your problem, you can always send me your demo project. So maybe I can fix it for you.
Left by Jeroen Bourdeaud'hui on Feb 18, 2012 12:34 AM

Your comment:
 (will show your gravatar)

Copyright © Jeroen Bourdeaud'hui | Powered by: