Failing to catch the return value from a stored procedure in ASP Classic

Apologies for the lengthy post, but I wanted to provide all the necessary details.

I am facing an issue with a JavaScript function that uses ajax to call some asp code, which then executes a stored procedure to check if a record already exists. Depending on the result, different images are displayed. The problem is that I am unable to capture the results in my asp variable, leading to empty returns and false outcomes. Despite testing the SQL procedure separately and confirming the data exists, I can't seem to retrieve it in my code. Here's the code snippet for better understanding:

Stored Proc:

ALTER PROCEDURE [dbo].[UserName_Get] 
    -- Add the parameters for the stored procedure here
    @UserName nvarchar(50)
    ,@FacilityID INT
    ,@UserNameExists INT OUT
AS

BEGIN
    SELECT @UserNameExists= ISNULL((SELECT UserID FROM MyTable WHERE FacilityID = @FacilityID AND Username = @UserName),0)

END

Classic ASP code:

<% Response.Buffer = True %>
<!-- #include file="../../_app_init.asp" -->

<%
Dim action, p_UserName
action = SqlSanitizeStr(trim(request("action")))

If action = "CheckUserName" Then

    p_UserName=SqlSanitizeStr(trim(request("UserName")))


    Set objCmd = Server.CreateObject("ADODB.Command")
    Set objCmd.ActiveConnection = DB_CONN
    objCmd.CommandText = "UserName_Get"
    objCmd.CommandType = adCmdStoredProc
    objCmd.Parameters.Append objCmd.CreateParameter("@UserName",        adLongVarChar,      adParamInput,   50        , p_UserName)
    objCmd.Parameters.Append objCmd.CreateParameter("@FacilityID",      adInteger,      adParamInput,           ,   LOGIN_FACILITY_ID)
    objCmd.Parameters.Append objCmd.CreateParameter("@UserNameExists",      adInteger,      adParamReturnValue)
    objCmd.Execute ,, adExecuteNoRecords
    UserNameExists = objCmd.Parameters("@UserNameExists").Value 

    If UserNameExists>0 Then

        Response.Write ("True")

    Else
        Response.Write ("False")

    End If

End If



%>

JavaScript Ajax Call

<script type="text/javascript">


  function CheckUserName(UserName_element) {


    var UserName = UserName_element.value;
    var valid_UserName_image = document.getElementById('valid_UserName_image');
    var invalid_UserName_image = document.getElementById('invalid_UserName_image');

    $j.ajax({
        data: { action: 'CheckUserName', p_UserName: UserName },
        type: 'GET',
        url: 'page_logic/_check_username_ajax.asp',
        success: function (result) {

            //Just to see what the return value is
            alert(result)

            if (result == "True") {


                valid_UserName_image.style.display = "none";
                invalid_UserName_image.style.display = "inline";

            }
            else {

                valid_UserName_image.style.display = "inline";
                invalid_UserName_image.style.display = "none";

                }

            }
        }
    );

}


</script>

An inspection using alert(result) shows that the return value is always empty.

If I modify the stored proc to simply

 SELECT @UserNameExists=0 or SELECT @UserNameExists=1

It will return a value, although this approach involves hardcoding the result rather than fetching records from the database.

Answer №1

The confusion arises from the incorrect usage of OUTPUT and RETURN in SQL Server stored procedures.

To clarify, your stored procedure expects an OUTPUT parameter rather than a RETURN value, which serves a different purpose.

Consider updating your output parameter declaration to:

objCmd.Parameters.Append objCmd.CreateParameter("@UserNameExists", adInteger, adParamOutput)

It's worth noting that adParamReturnValue is specifically designed to handle the return value of the RETURN statement, particularly for integer values.

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

Transferring data between two screens within an Ionic app by harnessing the power of angularJS

As a beginner in Ionic and Angular development, I am currently facing an issue with my Ionic application. I have two pages - one with drop-down selects and a submit button, and another page to process the user's choices and display the results. The pr ...

Fade out the div element when clicked

For my game project, I needed a way to make a div fade out after an onclick event. However, the issue I encountered was that after fading out, the div would reappear. Ideally, I wanted it to simply disappear without any sort of fade effect. Below is the co ...

When using ng-repeat in Angular.js, an additional td is created

https://jsfiddle.net/gdrkftwm/ https://i.sstatic.net/CTi2F.jpg I have encountered a problem while creating a table from a Json object. There seems to be an extra td being generated, and I'm not sure why. I want the structure of my table to resemble ...

How are the script name and script file connected in WordPress enqueuing?

When adding a jQuery script to the function.php file using the enqueue method, how does the script name relate to the actual file that contains the jQuery code? Is the script name arbitrary, or is it derived from either the file name or the actual script w ...

What could be causing the npm mysql module to malfunction when trying to initiate the 'connect()' function in a separate .js file?

When I call require('mysql') and use the function connect() everything works fine. However, if I try to call the 'connect()' function in another file, it throws an error saying connection.connect is not a function... Any suggestions on ...

Tips for utilizing document.write() with a document rather than just plain text

Currently, I am utilizing socket.io to develop a party game that shares similarities with cards against humanity. My main concern is how to retain the players' names and scores without needing to transmit all the data to a new page whenever new games ...

Interoperability between AngularDart and AngularJS

Discovering the Dart language and AngularDart after working with AngularJS has been exciting. However, my biggest concern is whether AngularDart supports all the amazing modules that AngularJS offers. I haven't been able to find any information on whe ...

Making an Ajax request using HTTPS in an HTTP environment

My website currently utilizes both http and https protocols without impacting the content. It incorporates jQuery ajax calls to populate certain sections of the page. However, I have a preference to transition all ajax calls to https protocol. Despite thi ...

Choosing various files from separate directories within an HTML input type="file" element

Is there a way to select multiple files from various directories using the HTML input type="file" element? I have been searching for resources on how to do this without any luck. Are there any npm packages that can assist with achieving this functionalit ...

Utilize the parsing functionality in three.js to extract JSON geometry data

After exporting a model from Blender using the three.js exporter and successfully loading it with the JSONLoader, my next challenge is to store the JSON information in a variable and parse it to display the model without having to load an external file. T ...

Looking for a JavaScript function that will enable the acceptance of commas and spaces

How can I modify this integer validation function to allow for commas and spaces to be entered during the keydown event? function intValidate(event) { if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || even ...

Displaying a text in a Django template as a JSON entity

I am currently facing a challenge with an angular app that sends JSON data to a Django backend. The Django application saves the JSON data into a database and later retrieves it to send it back to the angular app. However, I am struggling to get this entir ...

Managing authentication during an ajax call from an MVC client to the resource API within Identity Server 4

Authentication in my system is handled by Identity Server 4. One of the client's applications is an Asp.net core MVC Project, which needs to make ajax requests to a web API resource. From certain pages on the MVC client, I need to call the web API re ...

Utilizing the js-yaml library to parse a YAML document

Currently, I'm utilizing js-yaml to analyze and extract the data from a yaml file in node js. The yaml file consists of key-value pairs, with some keys having values formatted like this: key : {{ val1 }} {{ val2 }} However, the parsing process enco ...

JS: Initiating a new keypress operation

When I press the Tab key, I want it to do something different instead of its default action. Specifically, I have a text box selected and I would like it to add spaces (essentially making the textarea behave like a text editor). How can I trigger this type ...

Continuously calculate the sum of nested values until the foreign key becomes no longer relevant

I've been struggling to create a data retrieval function that can accurately sum up the count of all voorwerpnummers in the Voorwerp_in_Rubriek table, grouped by their rubrieknummer from Rubriek. I need to loop through these sums to reach their ' ...

The final version of the React App is devoid of any content, displaying only a blank page

As a beginner in learning React, I must apologize for any basic issues I may encounter. I recently created a shoe store App (following this helpful tutorial on React Router v6) Everything seems to be working perfectly in the development build of my app. ...

Exploring Objects without the need for loops

Currently, I am focusing on optimizing the performance of the following objects: var scheduleFee = { poor = {level1:25,level2:25,level3:25} , good = {level1:15,level2:20,level3:25} , vgood = {level1:10,le ...

In Node.js, it is essential to use req.session.save() to ensure that sessions are properly saved

While developing a website with Node.js, Express, and Redis for session management, I noticed an issue where my session variable (isLoggedIn) wasn't being saved after refreshing the page. Strangely, calling req.session.save() after setting the variabl ...

Perl's powerful capabilities allow for the creation of interactive drop-down menus

As a newcomer to web programming, I have recently been tasked with scripting projects during my summer internship. I've been utilizing Perl to develop CGI scripts for my company's internal website, specifically catering to the needs of the develo ...