Utilize a WCF Service with HTML and JavaScript

FILE WebService.svc.vb

Public Class WebService
    Implements IWebService
    Public Function Greetings(ByVal name As String) As String Implements IWebService.Greetings
        Return "Greetings, dear " & name
    End Function
End Class

FILE IWebService.vb

Imports System
Imports System.ServiceModel

<ServiceContract()>
Public Interface IWebService

    <OperationContract()>
    Function SendReport(ByVal name As String) As String
</Interface>

FILE Web.config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="WebService">
        <endpoint address="WebService" binding="basicHttpBinding" contract="IWebService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

      </service>
    </services>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

FILE WebService.svc

<%@ ServiceHost Language="VB" Debug="true" Service="WebService.WebService" CodeBehind="WebService.svc.vb" %>

I am currently hosting this service remotely in IIS 7(.5 possibly) and now I wish to integrate it into a web application. The web application is built using jquery and adheres to standard HTML5 guidelines. Numerous examples exist demonstrating the consumption of a WCF Service with javascript or AJAX. Therefore, I am seeking guidance on implementing code that accomplishes this, alongside necessary modifications to my web.config file (or any other adjustments required by the service) to enable this type of integration.

Answer №1

If everything is operating smoothly with your service, there's no need to make any changes on the server side. Your web service functions independently from the client that calls it. To test your service, consider using a tool like SoapUI.

You can use the following HTML snippet as a client for your service, making sure to adjust the post URL to match yours. This code demonstrates posting json data:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://w3c.dtd/xhtml1-transitional.dtd">
<html xmlns="http://w3.org/1999/xhtml">
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("a#CallService").click(function (e) {
          e.preventDefault();

          $.ajax({
            type: 'POST',
            data: '{"name": "' + $("input#name").val() + '"}',
            url: 'http://targetURL/Hello',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success:
              function (data, textStatus, XMLHttpRequest) {
                alert(data.d);
              },
            error:
              function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
              }
          });
        });
      });    
    </script>
</head>
<body>
  <input id="button" /><a id="CallService" href="#">Test</a>  
</body>
</html>

I hope this provides some assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to locate the specified view within AngularJS framework

<!doctype html> <html lang="en" ng-app="phonecatApp"> <head> <script src="/js/angular-1.5.2/angular.js"></script> <script src="/js/angular-1.5.2/angular-route.js"></script> <script src="/js/app.js">< ...

Employ a data or computed property that relies on the value of the prop. The prop will be changed

I'm trying to open a modal in Vue, but I keep getting this error message in the console from the navigator: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed ...

Display or conceal a div element individually

My task involves modifying this code, which is the original version of a FAQ with three answers that can be toggled to show or hide on click. I need to revise it so that only one answer is displayed at a time and the others close. I received advice to us ...

Retrieve a targeted data value from a JSON object based on an array value

Looking at the JSON array and another array provided below. JSON OBJECT { id: 1, name: 'abc', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfbebdbc9fb8b2beb6b3f1bcb0b2">[emai ...

At times, the animation in SetInterval may experience interruptions

I have created an animation using a sequence of images. The animation runs smoothly with the setinterval function, but for some reason, it occasionally pauses. I've shared a fiddle where you can see this pause happening. Click Here to See the Unwante ...

What is the best way to connect these functions in a sequence using promises?

A new software has been developed to extract data from an online t-shirt store and then organize the product information into a CSV file. The software consists of 3 scraping functions and 1 function for writing the data. I'm currently facing challen ...

Activate the div when hovering over the span

Experiencing an issue with triggering a visible div while hovering over a span. Here is the code structure: <ul class="products"> <li> <a href="somelink"> <img src="some image"> <div class="overlay"> Some Text</div> & ...

React not displaying wrapped div

I am facing an issue with my render() function where the outer div is not rendering, but the inner ReactComponent is displaying. Here is a snippet of my code: return( <div style={{background: "black"}}> <[ReactComponent]> ...

Issue encountered: Incompatibility between Mongoose Populate and Array.push()

After reading a different post addressing the same issue, I still couldn't figure out how to implement the solution into my own scenario. The discussion revolved around the topic of node js Array.push() not working using mongoose. In my Mongoose asyn ...

Adding methods to a constructor's prototype in JavaScript without explicitly declaring them

In the book Crockford's JavaScript: The Good Parts, there is a code snippet that demonstrates how to enhance the Function prototype: Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; }; Crockford elabo ...

Issue accessing member value in inherited class constructor in Typescript

My situation involves a class named A, with another class named B that is inherited from it. class A { constructor(){ this.init(); } init(){} } class B extends A { private myMember = {value:1}; constructor(){ super(); ...

Securing access across multiple routes in a React application

I am facing a challenge in my React app where I need to verify the logged-in state before allowing access to multiple routes. Despite consulting various resources like Stack Overflow for solutions such as creating a Private Route, I have only found example ...

Is there a way to recycle an image and ensure that the web browser only needs to download it once?

Is there a way to effectively reuse the same image multiple times on my website without inefficiently downloading it each time? ...

A method to trigger the opening of a div tag when a button is clicked using Vue.js

<div class="input-wrapper"> <div class="mobile-icon"></div> <input class="input-section label-set" type="text" v-model.trim="$v.mobile.$model" :class="{'is-invalid': ...

Retrieve data from a ng-repeat variable within a controller

Below is the current code snippet: HTML <center><li ng-repeat = "x in items | orderBy: 'priority'"> <!-- color code priorities --> <span ng-style="cmplt" ng-class="{ red: x.type == &apo ...

Scroll horizontally within the div before scrolling down the page

After reviewing other questions, it's important to note that the scroll I am looking for is horizontal, not vertical. My goal is to have a div on a page automatically start scrolling when it reaches the center or becomes visible, and then allow the pa ...

Unfulfilled promises are left hanging

I've encountered a problem while writing a unit test for my Angular application using Jasmine with a mock service. The promise I am trying to run is not functioning as expected. Below is the service code: CreateItemController = $controller('Cre ...

I encounter an issue with the ng-repeat in my code

It appears that the rendering is not working properly. http://plnkr.co/edit/IoymnpSUtsleH1pXgwFj app.controller('MainCtrl', function($scope) { $scope.lists = [ {"name": "apple"}, { "name": "banana"}, {"name" :"carrot"} ]; }); ...

Troubleshooting why the Angular innerHTML function is failing to render the specified

I'm encountering this problem where I am receiving a string const str = '<p>Please ensure Process Model diagram represents Functions adequately (boxes that represent an activity or group of activities that produce an outcome):</p>< ...

Is there a way to switch (transpose) the rows and columns of a dynamically generated HTML table from Highchair in Angular 12?

Click here to view the code for creating a highchart table. In the provided example, I have successfully implemented a highchart table using the code below. Highcharts.chart('container', { title: { text: 'Solar Employment Growth by Sec ...