The C# function doesn't get invoked properly when attempting to call it with Ajax Javascript upon clicking an asp:Button

Whenever I enter a value in the textbox and click on the "Save" button, I want to check if that value already exists in the database. If it does, then I need to display an alert saying "Value already exists". To achieve this, I am using Ajax Javascript along with an asp:Button ("Save") click event:

Ajax Javascript:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("[id*=btnBar]").bind("click", function () {

                alert("helloooo");

                var chk = {};
                chk.requestID = $("[id*=lblGuidId]").text();
                alert(chk.requestID);
                chk.barCode = $("[id*=txtBar]").val();
                alert(chk.barCode);

                $.ajax({
                    type: 'POST',
                    url: "Demo.aspx/SaveUser",
                    data: '{chk: ' + JSON.stringify(chk) + '}',
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function (data) {

                        var val = data.isUserInserted;
                        alert(val);

                        if (val == true) {
                            alert("Barcode No. alredy exist");
                            window.location.reload();
                        }
                        else {
                            alert("Barcode No. does not exist");
                        }
                    },
                    error: function (data) {
                        alert("error" + data);
                    },
                });
                return false;

                alert("End click");
            });
        });       
    </script>

HTML code:

<asp:Label ID="lblGuidId" runat="server" Text='<%# Bind("RequestID") %>'></asp:Label>
<asp:TextBox ID="txtBarcodeNumber" runat="server" MaxLength="11" Width="230px" Text='<%# Bind("BarcodeNo") %>' Display="None" OnTextChanged="TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:Button ID="btnBar" runat="server" Text="Save"/>

c# Code:

public class Check
{
    public Guid? requestID { get; set; }
    public string barCode { get; set; }
}

[WebMethod]
[ScriptMethod]
public static bool SaveUser(Check chk)
{
    bool isUserInserted = false;

    string strcon = ConfigurationManager.ConnectionStrings["MasterDB"].ConnectionString;
    SqlConnection con = new SqlConnection(strcon);
    using (SqlCommand cmd = new SqlCommand("Invoice.usp_tbl_Request_Select_CheckDuplicateBarcode_Test", con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@RequestID", chk.requestID);
        cmd.Parameters.AddWithValue("@BarcodeNo", chk.barCode);
        cmd.Connection = con;
        con.Open();
        isUserInserted = Convert.ToBoolean(cmd.ExecuteScalar());
        con.Close();
    }
    return isUserInserted;
}

However, every time it goes into the else part, even when the data exists in the database. My goal is to show the alert "already exist" if the C# WebMethod bool isuserInserted returns true, and "does not exist" if it returns false.

Please let me know what might be missing in my code.

Note that this is my first time working with Ajax Javascript.

Answer №1

When working with certain versions of .net, it is important to add a datafilter to ensure that the correct information is obtained:

While using data.d may be sufficient, including the dataFilter function makes the code version-proof. This way, it will work regardless of the version you are using and eliminate the need to make changes when updating or upgrading your server-side version.

You can achieve this by implementing the following function:

dataFilter: function(data)
    {
        var msg;
        if (typeof (JSON) !== 'undefined' &&
        typeof (JSON.parse) === 'function')
            msg = JSON.parse(data);
        else
            msg = eval('(' + data + ')');
        if (msg.hasOwnProperty('d'))
            return msg.d;
        else
            return msg;
    },

Your ajax call code should then resemble the following example:

$.ajax({
    type: 'POST',
    url: "Demo.aspx/SaveUser",
    data: '{chk: ' + JSON.stringify(chk) + '}',
    contentType: 'application/json; charset=utf-8',
    dataFilter: function (data) {
        var msg;
        if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') msg = JSON.parse(data);
        else msg = eval('(' + data + ')');
        if (msg.hasOwnProperty('d')) return msg.d;
        else return msg;
    },
    dataType: 'json',
    success: function (data) {

        var val = data.isUserInserted;
        alert(val);

        if (val == true) {
            alert("Barcode No. already exists");
            window.location.reload();
        } else {
            alert("Barcode No. does not exist");
        }
    },
    error: function (data) {
        alert("An error occurred: " + data);
    },
});

Answer №2

Try using
const value = data.result in place of value = data.isUserNew.

This should do the trick.

Answer №3

Start by verifying the output of alert(val) to confirm its accuracy. Next, employ the === operator for strict equality comparison, considering both value and data type, or convert the value val to a Boolean.

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

Utilize AJAX to submit datetimes to an ASP.NET Core controller via a POST request

I'm encountering an issue where the values from the datepicker are not being passed to the controller and are always null on the controller side. I have tried looking at other discussions on this topic but haven't found a solution. $(function Ge ...

Insert items into a frozen map

I'm dealing with an immutable map and iterating through an array to create objects that I want to place inside the map. What would be the correct approach to achieve this? Below is my current code snippet: let arrayOfNames = ['John', ' ...

Is it possible to use jQuery to add something to the end of

There are two URLs that I am working with: http://blah.com/blah/blah/blah and http://shop.blah.com/. My goal is to take the domain from the first URL (blah.com) and concatenate it with the path (/blah/blah/blah) from the second URL, resulting in http://sho ...

Understanding the unpredictability of A-Sync in Node.js/Express: Why does it appear to operate in a non-linear fashion?

Recently, I delved into the world of Node.js/Express and encountered asynchronous calls that must complete before moving on. My code features three different endpoints that need to be hit. Considering the asynchronous nature, I attempted to structure my c ...

WCF REST: How should the XML format be structured in requests?

Within my WCF service, I have a method structured as below: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml)] public int GetOne(string param1 ...

The function Router.use() is in need of a middleware function, but instead received an undefined

A snippet of code from my index.js file looks like this: ... import userRoutes from './src/routes/userRoutes'; import invoicesRoutes from './src/routes/invoicesRoutes'; import authMiddleware from "./src/middlewares/authMiddleware"; ... ...

Retrieving data from MySQL with Angular and Laravel

I have a task of retrieving data from my database, updating one div and then updating another div when clicked. I was able to fetch the data successfully, but I am facing issues in updating the additional content on click. Here is my code: var app = an ...

Arranging the local storage scores in increasing order

I am trying to organize the table data in ascending order, with the person having the highest score appearing at the top and the person with the lowest score at the bottom. I have been working on creating an array and using a for loop to sort the data ac ...

Successfully executing a JQuery ajax GET request results in receiving truncated data

Recently, I encountered an issue while retrieving a large amount of data from my server using a JQuery ajax GET request. The data returned was truncated unexpectedly (as shown in the image below). However, when I tried accessing the same URL directly throu ...

I am experiencing difficulties with Chai assertions not functioning properly in my JavaScript and Webdriverio framework/method

I am currently using an object modeling approach to mirror pages and initializing the chai libraries within the wdio file. However, my method seems to be failing. Any suggestions? Here is the method I am using: confirmSuccessfulSubmission() { const s ...

Issue with Flex property not being supported in Safari browser

.rq-search-container { position: relative; width: 100%; background: white; display: flex; flex-direction: row; align-items: flex-start; border-radius: 2px; z-index: 30; -webkit-flex: 1 0 15em; } While this code functi ...

Ajax request and the Ghostery extension in Firefox

I've implemented the following code to detect ad blockers like Ghostery: <script> var request = new XMLHttpRequest(); request.onreadystatechange = function() { if(request.readyState === 4 && request.status === 200 ) { ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

MasteringNode: Exercise 3 The Beginning of My Journey with Input and Output

While working in Visual Studio Code on Windows 10 using powershell.exe as my terminal, I encountered a problem that I couldn't solve on my own. After numerous attempts, I decided to search the internet for a solution, and here's what I found: v ...

The execution of Ajax is not taking place

Hey, I'm facing an issue with AJAX in my project. It's working fine in other files, but for this specific instance where I call scripts/claim.php and pass an id parameter via GET, it's not functioning as expected. HTML <input type="hidd ...

How come I'm getting a numerical output instead of an array after using the array.push() method in this code?

In need of a custom function to append an element to the end of an array, I encountered a requirement: if this new element shares its value with any existing elements in the array, it should not be appended. For instance, adding 2 to [1,2] should result in ...

Is there a way to automatically display the detailsPanel in Material-table upon loading?

I am currently working on creating a subtable for the main React Material-Table. So far, everything is functioning correctly as expected, with the details panel (subtable) appearing when the toggle icon is pressed. Is there a way to have it displayed by d ...

retrieving data from GET variables and sending to a PHP array

Is there a way to retrieve form variables and store them in an array in memory without reloading the page? I'm not very experienced with this, so any guidance would be appreciated. My goal is to update a JSON file using PHP based on form inputs. JSON ...

Error in establishing the connection for Pushsharp 4.0.10.0 ApnsConfiguration with iOS device tokens

Currently, I am utilizing the PushSharp 4.0.10.0 library to send notifications to iOS devices, however, it seems to be encountering issues. Upon debugging, I have identified a connection problem with the ApnsConfiguration. This is the code snippet I am us ...