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

Encasing common functions within (function($){ }(jQuery) can help to modularize and prevent

As I was creating a global JavaScript function and made some errors along the way, I finally got it to work after doing some research. However, while searching, I came across an example using (function($){ code here }(jQuery); My question is, what exact ...

Using PlayFramework: How to implement Ajax, Drag and Drop functionality, and File Upload with File object in the controller?

Is there a method to upload a file through Ajax and drag-and-drop from the desktop while also supporting PlayFramework's capability to convert file uploads into a File object? I have experimented with multiple approaches, but none seem to be function ...

Determining when all textures have successfully loaded in Three.js and ensuring there are no lingering black rectangles

I'm currently developing a web platform that allows users to customize and preview 3D house models. If the user's browser doesn't support WebGL, the server renders the house and sends screenshots to the client. However, if the screenshots ar ...

Incorporating an HTML page into a dialog using AngularJS: A step-by-step guide

Is it possible to dynamically change the content of a dialog by updating the URL? I have multiple HTML pages that I want to display in my dialog by simply changing the URL. <md-button ng-click="showDialog($event,'myurl/page-1.html')">Show ...

Generating a JSON download link using AngularJS

I'm attempting to generate a link that will enable the download of a JSON file in this way Controller $scope.url = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj)); View <a href="url" download="download.json">downlo ...

JavaScript for validating dimension text input has unique functionalities

I am looking for guidance on validating an ASP textbox using JavaScript. My goal is to validate a user's input in the format of 4-1/2, 80-1/2, 6/8, or simply 5. Only these types of patterns should be allowed, and each input must contain only one numbe ...

What is the best way to retrieve and display a well-structured JSON object in a Node

I am currently working on setting up a nodejs server with the following code: var http = require('http'); var port = 1337; http.createServer(function(req, res) { var statusList = { "hasErrors": false, "list" : [ { "id": " ...

Looking for a way to access the source code of a QML method in C++?

I'm currently working on serializing objects to QML and I am looking for a way to retrieve the source code of functions defined within a QML object. Let's consider the following example in QML (test.qml): import QtQml 2.2 QtObject { functio ...

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...

Retrieve the selected option from the dropdown menu in the specified form

What should I do if I have numerous products and want users to be able to add new dropdown boxes dynamically? When the submit button is clicked, only the value of "category[]" within the form should be retrieved. https://i.stack.imgur.com/v1fnd.png Below ...

Steps for creating a sleek vertical slider with transitional effects using JavaScript and HTML

Take a look at my code snippet: <table> <tr> <td onclick="shownav()">Equations of Circle <div id="myDownnav" class="sidenav"> <a>General Info</a> <a>In Pola ...

Maximize the performance of Express and Swig to boost HTML rendering efficiency

I encountered a significant problem. Here is the breakdown of my application architecture: nginx -> web app (express/nodejs) -> api (jetty/java) -> mysql The performance of the API application is optimized, with response times around 200ms/req ...

Exploring the power of Node.js and EJS through the art of

Recently delving into the world of node.js, I encountered a puzzling issue with my EJS template. It seems that my for loop is not executing properly within the EJS template while attempting to create a basic todo app. Below is the structure of the project ...

Validation of user input alongside input masking using jQuery

One issue that I am encountering is that form inputs with assigned masks (as placeholders) are not being validated as empty by jQuery validation. I am using: https://github.com/RobinHerbots/jquery.inputmask https://github.com/1000hz/bootstrap-validator ...

Find the months where two date ranges overlap with the help of date-fns

Is there a way to find the overlapping months between two date intervals using date-fns? const range1 = { start: new Date('2018-01-01'), end: new Date('2019-01-01') } const range2 = { start: new Date('2018-07-03'), end: new D ...

Verify if the nested JSON object includes a specific key

Currently, I am grappling with a dilemma on how to determine if within a deeply nested JSON object, featuring numerous unknown arrays and properties, lies a specific property that goes by the name "isInvalid". My objective is to identify this property and, ...

An absence of data causes the function to malfunction

One of the components in my application is responsible for rendering select elements on the screen, allowing users to dynamically order data. The initial state is as follows: state = { sortBy: [ { author: 'asc' } ] }; In this s ...

Having trouble extracting the date modified from a JSON file

I am able to retrieve section name, URL, web title, and headline from parsing JSON data with this code snippet. However, I seem to be encountering an issue where I cannot extract the last modified date. Here is the JSON structure: { "response":{ ...

Retrieve the class using a text string and then obtain the subsequent string

I am searching for the first class containing the text "Routed:" and then I want to retrieve the following string. I attempted to utilize document.querySelector, but I'm uncertain if this is the correct approach. <td class="msvb2">Routed:</t ...

Utilizing React JS to neatly display Firebase data in a table

Before I post, I always make sure to do my due diligence by searching on Google, YouTube, forums, or trying to figure it out on my own. I even check questions similar to mine asked by other people, but unfortunately, I'm stuck. Currently, I am using ...