The function validateLogin is not defined within the code, resulting in a javascript exception being

Hey there, I'm encountering an undefined function error and I believe my code is correct. Can someone please offer assistance in this situation? Additionally, could you recommend a good tutorial for fetching data through a webservice using the Ajax method?

<script type="text/javascript" language="javascript" src="Scripts/jquery-1.4.1.js">

  function validatelogin() {

        $('input[type=button]').attr('disabled', true);
        $("#login").html('');
        var loginId = $('#txt_id').attr('value'); // retrieve username
        var password = $('#txt_pwd').attr('value'); // retrieve password

        $.ajax({

            type: "POST",
            url: "WebService.asmx/validateLogin",
            data: "lognId=" + loginId + "&password=" + password,
            contentType: "application/json; charset=utf-8",

             success: function (result) {
                    returnVal = result.d;
                    alert(returnVal);
                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    returnVal = '';
                    },
        });
     }


</script>

Answer №1

It is not recommended to link a JavaScript source file and include code within the same tag. It is best practice to separate them into two different tags as shown below:

<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
  function validatelogin() {

        $('input[type=button]').attr('disabled', true);
        $("#login").html('');
        var loginId = $('#txt_id').attr('value'); // get username
        var password = $('#txt_pwd').attr('value'); // get password

        $.ajax({

            type: "POST",
            url: "WebService.asmx/validateLogin",
            data: "lognId=" + loginId + "&password=" + password,
            contentType: "application/json; charset=utf-8",

             success: function (result) {
                    returnVal = result.d;
                    alert(returnVal);
                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    returnVal = '';
                    },
        });
     }


</script>

Referencing MDN documentation:

src

This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document. Script elements with an src attribute specified should not have nested script tags.

Answer №2

Your request is set to have a content type of JSON, but you are actually passing name-value pairs. Here is a solution for you:

data: JSON.stringify({loginId: loginId, password: password}),

Additionally, instead of using attr('value') to get input value, consider using val() as a more efficient alternative.

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

Having trouble getting the jQuery function to update text properly

I'm curious to understand the behavior happening in this code snippet. It seems like updating the list item by clicking doesn't work as expected using the initial method. But when rearranging the JavaScript code, it displays the correct value wit ...

When trying to run the "npm start" command, I encountered a syntax error that specifically mentioned the use of

Every time I attempt to run the npm start command, I encounter the following error: I have followed the steps provided in this link: https://github.com/kriasoft/react-starter-kit/blob/master/docs/getting-started.md Could you please advise on how to resolve ...

Adding jQuery and other libraries to Typescript for optimal functionality

After spending days researching and struggling, I am reaching out here for clarification on the process of importing a library in Typescript. I used to just add the script tag and everything would work fine. Now that I am working on building a MEAN-Stack ...

What are the steps to implement localStorage in Vuejs3?

I'm feeling a bit lost when it comes to localStorage and its usage. I have a component called Statistic.vue which displays a modal at the end. Statistic.vue <template> <p class='modal'>{{numberOfGames}}</p> </template& ...

A guide to displaying a JSON object in a Jade template and iterating through the data

When I pass a JSON string to a jade file for rendering, I am facing an issue where I can only print the entire string and not its individual elements. How can I print specific elements or iterate through the JSON string? app.js: var http = require(&ap ...

Dealing with field errors on ajax forms in CakePHP

CakePHP offers a fantastic Error Validation feature where all errors are automatically displayed next to each field in the view. It works flawlessly. However, things get tricky when trying to implement this with Ajax. Is there a way to streamline this pro ...

Having difficulty accessing any of the links on the webpage

I'm currently utilizing the selenium webdriver to automate a specific webpage. However, I am encountering an issue where my selenium code is unable to identify a certain link, resulting in the following error message. Exception in thread "main" org ...

Changing the caret position in a contenteditable div using HTML React

In a recent project I worked on, I included contenteditable divs. Whenever the enter key is pressed within one of these divs, it splits into two separate contenteditable divs. However, after React re-renders the components, the caret tends to go to the beg ...

pg-promise received an error due to an incorrect parameter being passed in for options

I have been working on transitioning my files from utilizing the pg package to the pg-promise package. Initially, everything was functioning correctly with the original pg solution I had in place. However, upon switching to pg-promise and referencing the d ...

Issues with ASP.NET 2.0 callbacks persisting in Firefox browsers

I have developed a .NET Web control that utilizes the callback structure implemented in ASP.Net 2.0. This control, an autodropdown, functions flawlessly in IE 6.0/7.0 and Google Chrome. Below is the pertinent callback function: function ReceiveServerData( ...

What is the best way to store chat messages in a React application?

My idea for a chat application using React involves saving chat messages in localStorage. Below is the code snippet that illustrates this functionality: const [textMessages, setTextMessages] = useState([]); const [textValue, setTextValue] = useState(' ...

How can checkboxes be combined from two separate tables?

Within this interactive code example, you will find two tables containing checkboxes in each row. Upon clicking the To button, a dialog box will appear allowing you to select users or groups from a drop-down menu. The corresponding tables will then be dis ...

The timer countdown is encountering an issue where it cannot update the 'textContent' property of a null element

I'm encountering errors with a countdown script that I can't seem to resolve. The error message is generating 1 error every second: Uncaught TypeError: Cannot set property 'textContent' of null at (index):181 (anonymous) @ (index):181 ...

Sliding elements horizontally with jQuery from right to left

I recently purchased a WordPress theme and I'm looking to customize the JavaScript behavior when the page loads. Currently, my titles animate from top to bottom but I want to change this behavior dynamically. You can view it in action here: I have ...

Tips for designing a user interface for a security software product

We have created a cutting-edge security tool that can detect unauthorized network traffic. The user interface for displaying alerts is generated by a Java Servlet page. Currently, the page functions as a sophisticated console log. It features a large text ...

Is it possible to save round items within a session?

While utilizing Blocktrail's API for bitcoin wallet management, I encountered an issue with circular references within the returned wallet object. The goal is to store the decrypted wallet in the user's session to avoid password re-entry. Howeve ...

Utilizing JSON in a d3.js application within a Rails environment

I have been exploring the gem gon in order to generate JSON data from my Rails database. I have successfully managed to display this data in an alert, but now I am looking to visualize it using d3.js. Within my database named "users" with columns (name:st ...

Choose the heading element based on its class

I am trying to target a specific element by its class and store it in a variable, but I specifically need this element to be a heading element. To clarify: at any given time, there are always exactly 3 elements with this particular class on my page: an < ...

Differences between MobX local state and global state

I am currently working on a React project using mobx to manage the application state. For dump components that interact with external data sources (such as ajax calls, filtering or mapping arrays), I simply manipulate the data in those components. Howeve ...

What is the proper way to utilize $apply and $watch in the Angularjs 1.4.10 Directive Structure?

`.directive('counter', function counter() { return { scope: {}, bindToController: { count: '=' }, controller: function () { function increaseCount() { this.count++; } function decreaseCo ...