Utilizing AJAX to call a web service

Trying to make a call to this web service via AJAX...

The structure of the web service is as shown below


        public class WebService1 : System.Web.Services.WebService
        {
        
            [WebMethod]
            public String countryCode(String input)
            {
        
                StringBuilder strings = new StringBuilder("", 10000);
                String text = System.IO.File.ReadAllText(Server.MapPath("countryCodes.txt"));
                String[] countries = Regex.Split(text, "#");
        
                var valids = new List<String>();
                foreach (String c in countries)
                {
                    if (c.ToUpper().StartsWith(input.ToUpper()) || c.ToLower().StartsWith(input.ToLower()))
                    {
                        if (input == "")
                        {
                            break;
                        }
        
                        valids.Add(c);
                    }
                }
                return (valids.Any()) ? String.Join(" ", valids) : "No results found for your input!";
            }
        
        }
    

I have created a blank web form and included the service reference in the script manager like this


        <body>
        <form id="form1" runat="server">
            <asp:ScriptManager ID="ScriptManager1" runat="server">
                <Services>
                    <asp:ServiceReference Path="~/WebService1.asmx" />
                </Services>
            </asp:ScriptManager>
    

Here is the javascript code I am using


        <script type= "text/javascript">
            var a = wRequest.set_userContext("user's context");
            var onClick = function () {
                CountryCodes.WebService1.countryCode($get("TextBox1"), onSuccess, onFailed);
            }
            var onSuccess = function (result) {
                $get("Label3").innerHTML = result;
            }
            var onFailed = function (result) {
                $get("Label3").innerHTML = "No results found for your input!";
            }
        </script>
    

When I click the button, nothing happens. The button code is as follows


        <input type="button" value="Find Country Codes " onclick ="onClick()" />
    

The button, textbox, and label code are in the same location. What am I doing wrong and how can it be resolved?

If you need further clarification, please comment below. Thank you.

Regards

EDIT : I have commented out this line in the web service

"[System.Web.Script.Services.ScriptService]"

Answer №1

To enable your web service class for JavaScript interactions, add the attribute

[System.Web.Script.Services.ScriptService]
to your class declaration:

[System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService

By doing this, you allow your JavaScript code to communicate with your web service.

Furthermore, when calling your web service, make sure to omit the CountryCodes prefix. Here's an example of the updated call:

var onClick = function () {
    MyWebService.countryCode($get("TextBox1"), onSuccess, onFailed);
}

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

Leveraging JSON response within a CFIF statement

Can the value of response.DATA[i][j] be used in a CFIF statement? chkUsernameUnique = function(theUsername){ $.ajax({ type: "GET", url: "/book.cfc", data: {method: "testFunction", datum: $('#date').val(), returnFormat: "JSON"}, ...

Easily upload numerous files simultaneously with just one click of a button

This particular element, <asp:FileUpload ID="FileUploadEventosCasal" runat="server" /> is designed to upload a single file at a time when the button is clicked. I am interested in finding out how it would be possible to upload multiple files in a ...

Leverage ConvexGeometry within the npm release of THREE

Is there a way to utilize ConvexGeometry in the npm version of THREE? It appears that it was introduced in r85: https://github.com/mrdoob/three.js/releases I noticed that it's only present in the example folder. Is there a method to incorporate it ...

vue v-if="canEdit" @click.prevent

I have a Vue component called 'test' with specific template and methods. The goal is to make the div clickable only if helper.isEditable is true, otherwise it should be notClickable or touchable. However, I can only retrieve the value of helper. ...

The input value does not update in the controller when using AngularJS ng-model

Why is it that when I print out console.log($scope.inputvalue), the variable does not update with the values I enter in the input field? Did I misunderstand the purpose of ng-model? If so, how can I pass a value from the view to the controller? (functi ...

Difficulty in retrieving a file from another thread within Asp.net

My website, built on Asp.net 3.5 with Linq-to-Sql for data access, has a specific process that needs to be executed in a certain order: Upload a file Record and save file information in the database Import data from the file into the database Redirect to ...

Establishing and deleting wireless network configurations

I am interested in developing a tool to manage various aspects of wifi configuration. My goal is to create a tool that can delete existing network profiles by name and create new ones. While researching, I came across this resource that appears to assis ...

Use ajax request to serialize input into HTML value

I implemented a jquery.ajax post request to send data to the server using C#, however, I encountered an error with my code. Here is the code snippet: $(function(){ $('#frmSubmit').on('submit', function(e){ e.preventDefault(); ...

The Bootstrap navigation bar drop-down feature is not displaying the menu

After skimming through various threads on stackoverflow regarding the dropdown box in the navigation bar, none of the solutions seem to address my issue. Utilizing bootstrap version 3, I've implemented the provided navbar example from the official si ...

Having trouble accessing the downloaded file from S3 using Angular and NodeJS

Currently, I am facing an issue while attempting to download a jpg image from amazon S3 using the NodeJs SDK. Although I can successfully retrieve the file object on the backend, encountering difficulties arises when trying to create a blob object and down ...

Ways to handle errors when using navigator.clipboard.writeText

document.queryCommandSupported('copy') may not be available on all browsers. I experimented with the code below, which successfully copies the link on Firefox but fails on Opera. It displays an alert indicating that the code has been copied, yet ...

How can I effectively send a form with the value of 'put' using Laravel and Ajax?

I have been working on a function that utilizes AJAX to validate and send responses to the view when an edit form is submitted. However, I am encountering an issue where the page loads on a new URL like localhost:8000/comment/id, and I want the page to dis ...

Deciphering the AngularJS Component Hierarchy and Managing Identifiers for Freshly Generated Objects (using HTTP)

In my project using Angular 1, I have developed a todo list application which consists of two components. The first is a smart (container) component responsible for server-side interactions, while the second is a dumb/pure/stateless presentation component ...

Using jQuery UI datepicker - how to set a parameter based on a specific condition

New to the world of JavaScript, I am trying my hand at implementing the jQuery UI datepicker widget. My goal is to add an additional line to the widget parameters if the variable selectedDate has a value. However, my current approach seems to be ineffecti ...

What is the best way to send data from a header component to a separate container component?

Utilizing React-router-dom, I am able to seamlessly switch between components in the following setup: <Router> <div> <Header /> <NavigationBar /> <Switch> <Route exact path ...

What is the best way to indicate the selected item in the Menu List using Material UI React?

I am attempting to dynamically style the menu list items by toggling the selected prop between true and false. In order to achieve this, I am utilizing the onClick method to capture the event.target.name, update the state of the corresponding value associ ...

Updating WPF databindings occurs only when changes are made

After spending quite some time browsing through similar questions on SO, I am still struggling to understand why this particular issue is occurring. I have a Class with properties and a SeriesCollection used for Live Charts, which are bound to the UI. Due ...

What sets Observables (Rx.js) apart from ES2015 generators?

From what I've gathered, there are various techniques used for solving asynchronous programming workflows: Callbacks (CSP) Promises Newer methods include: Rx.js Observables (or mostjs, bacon.js, xstream etc) ES6 generators Async/Await The trend ...

Is there a way to generate a checkerboard dynamically with the help of jQuery?

I've made some progress so far, but I'm facing a challenge where I need to push 8 <td> elements into 8 different <tr> elements without hardcoding anything or modifying the HTML directly. Any help would be appreciated! JavaScript v ...

Ways to determine if prototype methods vary

Is there a technique to verify if functions are distinct despite originating from the same prototype? I'm inquiring because I want to save functions in an array, and when attempting to delete one, it removes all functions due to sharing prototypes. ...