JQuery ajax call to vb.net webservice

I’m a fan of all technologies. They all have strengths and off course their weaknesses. In this particular post i like to show how to go about posting to vb.net web service and how to retrieve the info back via JavaScript using the JQUERY library. Let’s get right into the code. I have a simple .net web service for the sake of this little tutorial I’m going to call it testajax. If you don’t know how to add a test service. Let me walk you through this.

1-start up visual studio or any IDE of your like or even notepad if that’s what you prefer.

2-start a new website for the and name it testajax.Pick asp.net web Service from the template options given to you.

 

3- Right click your app_code folder and add a new item.  Choose class from the list of available items and name the class genericObjects.vb. We are going to be using this class like a container to fill up and return and array of values.

4- Let’s name some variable in our class.

Imports Microsoft.VisualBasic

Public Class genericObjects

    Public Class largeObjects

        Public uno As String = String.Empty

        Public dos As String = String.Empty

        Public tres As String = String.Empty

    End Class

End Class

5. now let’s add some code to our webservice.

(This code goes into the Service.vb document)

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

<System.Web.Script.Services.ScriptService()> _

<WebService(Namespace:="http://tempuri.org/")> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _

Public Class Service

    Inherits System.Web.Services.WebService

    <WebMethod()> _

    Public Function HelloWorld(ByVal temp As String) As List(Of largeObjects)

        'System.Threading.Thread.Sleep(1500)

        'Dim LargeString As List(Of String)

        'LargeString.Add("hello")

        'LargeString.Add("uno")

        'LargeString.Add("dos")

        Dim r As New List(Of largeObjects)

        Dim r2 As New largeObjects

        r2.uno = "uno"

        r.Add(r2)

        r2.uno = "uno"

        r.Add(r2)

        r2.dos = "dos" + "dos" + "dos"

        r2.tres = "tres" + "tres" + "tres"

        r2.uno = "uno"

        r2.uno = "uno"

        r2.dos = "dos" + "dos" + "dos"

        r2.tres = "tres" + "tres" + "tres"

        r.Add(r2)

        Return r

    End Function

 

This is a very simple service it basically declares a variable named r of type list(of LargeObjects) which as you can tell its whats in our class.Then it fills the class with values. The multiple r.Add(r2) its just a way to get the values into separate list or arrays.

6- Now let’s add our html file. Right click your project and choose add a new item. Pick HTML page and name it default.aspx.

7- Let’s add some code to this file.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<script src="jquery.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>

 <title></title>

</head>

<body>

<!--http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/-->

<script>

    $(document).ready(function() {

        $('#Button1').click(function() {

            $(".result").html('<img src="ajax-loader.gif"/> ');

            $.ajax({

                type: "POST",

                contentType: "application/json; charset=utf-8",

                data: '{temp:"testval"}',

                url: "Service.asmx/HelloWorld",

                dataType: "json",

                success: getThevalues, //function(data) { $('.result').html(data.d); },

                //success: function(data)

                error: function(e) { $('.result').html("An Error Occured"); }

            });

        }); // end click

    });  // end .ready

    function getThevalues(data) 

    {

        for (var i = 0; i < data.d.length; i++) {

           // alert(data.d[i].uno);

            $('.result').append('<p>'+data.d[i].uno + '</p>' +"</br>");

            //$('.inner').append('<p>Test</p>');

        }

    }

</script>

<div class="box">

        <input id="Button1" type="button" value="Call WebService" />

        <div class="result">Call the webservice. </div>

</div>

</body>

</html>

Ok so let me explain the meat of this code  you are going to add a script section  in the body  of your file. Then you are going to  use

$(document).ready(function()

This line of code basically says don’t do this until the page is fully loaded.

Then we add an event listener to the click event of Button1 once that button is clicked it will trigger the ajax call.

The jquery Ajax function has a few parameters . You can use the ones you need and leave the other like I did in this example. The main thing I would like to point out in my example is this part

data: '{temp:"testval"}',

                url: "Service.asmx/HelloWorld",

                dataType: "json",

                success: getThevalues, //function(data) { $('.result').html(data.d); }

The data parameter is taking in the parameter I’m going to send in to the service. If the service those not required any parameters you can leave that parameter out. The URL is the parameter that says were your service is located. WARNING! You cannot call a web service in another domain without a proxy service. In other words if you have a service in another server that is not where this project is located. You will have to put a web service together In the current server and have that service call the other service.

The success function is the call back function that will be triggered when I received the values back from my service or the error function if I get an error.

hope you enjoyed this simple tutorial if  i missed something please pointed out i have no problem updating my post.

Thanks for visiting.

Leave a Reply

Your email address will not be published. Required fields are marked *