Stop the page from refreshing using asp.net, jquery, and javascript

Currently, I am working on creating a login page using asp.net and jQuery Mobile.

After the user clicks on the login button, I perform some processing in C# before calling the JavaScript function.

The issue I am facing is that when the login button is pressed, the page reloads before executing the JavaScript, which is not the desired behavior.

Below is a snippet of my code:

<asp:Button name="login" ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />

C#:

protected void btnLogin_Click(object sender, EventArgs e)
{
    if (String.Format("{0}", Request.Form["username"]) != "" && String.Format("{0}", Request.Form["password"]) != "")
    {

        ClientScript.RegisterStartupScript(GetType(), "key", "login();", true);

    }
    else
    {
        //todo
    }

}

JS/jQuery:

<script type="text/javascript>
    function login() {
        jQuery(function () {
            jQuery.ajax({
                beforeSend: function () {
                    $.mobile.loading('show', {
                        text: 'Processing...',
                        textVisible: true,
                        theme: 'a'
                    });
                }, 
                type: "GET",
                url: "Handler.ashx",
                data: "method=validate",
                success: function (data) {

                    $.mobile.loading('hide');
                    //$.mobile.changePage("HomePage.aspx", { transition: "fade" });

                }
            });
        });
    };
</script>

Do you have any thoughts or suggestions on this matter?

Thank you!

EDIT: I still require the server-side code for handling password encryption in C#

Answer №1

The OnClick event functions on the server-side, causing a postback. To execute client-side code before invoking the OnClick event, utilize the OnClientClick event instead.

Are there specific server-side tasks that must be completed before running the JavaScript? What is the objective of your operation?

Please provide a detailed explanation of the process flow for better understanding.

Answer №2

With this code snippet, you can take control of the click behavior on the user's browser. By using evt.preventDefault, you can prevent the button from triggering a re-load of the web page.

$('#btnSubmit').click(function(evt) {

    if(!checkCondition) {
        evt.preventDefault();
    }
    else{
    }
});

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

Tips for maintaining a healthy balance of tasks in libuv during IO operations

Utilizing Typescript and libuv for IO operations is crucial. In my current situation, I am generating a fingerprint hash of a particular file. Let's say the input file size is approximately 1TB. To obtain the file's fingerprint, one method involv ...

Effortless link to a Gremlin database using a JavaScript app

I apologize for my lack of technical knowledge, but I am struggling to solve this issue despite studying the documentation. My goal is to establish a connection with a standard Gremlin DB (Cosmos) using gremlin. While it works well from the server, encoun ...

Display a loading spinner during an HTTP request in Appcelerator

As of now, I am facing a challenge in displaying a spinner while an HTTP request is being executed. Every time I try to implement a spinner, it stops animating as soon as the call starts. var spinnerArray = []; for (var i = 0; i < 20; i++) { spinne ...

The Bootstrap modals seem to be invisible within the Rails application

Currently, I am integrating jquery into the devise views of a sample rails application. My intention is to test it on a sample app before implementing it in a production code. The controller and view for welcome are already set up. The routes.rb file loo ...

Issues with Javascript .map function failing to return accurate components

Encountered an issue with the .map method in my React project not returning the expected value. This is the desired output: const prepInfo = [ <PrepInfo uniqueKey={1} type={'prep'} quantity={'1'} unit={'unit'} suf ...

How do I automatically redirect to a different URL after verifying that the user has entered certain words using Javascript?

I want to create a function where if a user input on the "comments" id matches any word in my FilterWord's array, they will be redirected to one URL. If the input does not match, they will be redirected to another URL. The checking process should onl ...

Utilizing ng-class to manipulate arrays in AngularJS

Within my controller's $scope, there is an array called myElements... $scope.myElements = [false, false, true, false, true, false]; ...and I want to assign the class firstClass to a div element if any of the elements in the array are true, otherwise ...

What occurs when socket.io events are not properly handled?

Is socket.io ignoring or dropping messages? I am asking this because there is a client with multiple states, each having its own set of socket handlers. The server notifies the client of a state change and then sends messages specific to that state. Howeve ...

Using jQuery and JavaScript to swap images depending on the option chosen in a dropdown menu

On my existing ecommerce website, I have a dropdown menu with the following code: <select data-optgroup="10201" class="prodoption detailprodoption" onchange="updateoptimage(0,0)" name="optn0" id="optn0x0" size="1"><option value="">Please Selec ...

Is there a way to dynamically change the helperText of a Material UI TextField using its current value through code?

I'm currently attempting to dynamically change the helperText of a Material UI TextField based on the value entered into the field. Below is my current implementation: const defaultScores = { STR: 10, DEX: 10, CON: 10, INT: 10, WIS: 10, CH ...

Looking to perform an Ajax call to update a Rails model using HTML5 contenteditable, but encountering an issue where it creates a new

I am in need of assistance to update the plots of a story using HTML5 contenteditable feature. Below is the code snippet: Refer to file# for editing multiple plots <div id="editable" contenteditable="true"> <%= simple_format p.description %&g ...

Conceal the parent component's <button> element within the Child component

I'm facing an issue with hiding a button in my parent component from the child component. I tried using props to bind the element and v-show directive to hide it, but instead of just hiding the button, it ends up hiding the entire tab. Take a look at ...

Failure to update child props due to changes in the parent state

I am currently in the process of updating a child component based on the props provided by its parent. The current setup involves the parent's state having a 'paused' variable which is passed down to the child like so: class Parent extends ...

Having trouble importing components in NativeScript Vue?

I am just starting to explore the world of NativeScript and working on my first project using it. I am facing an issue while trying to incorporate a header component into my main App. Unfortunately, when I run the iOS emulator, the header does not appear o ...

Utilizing XHTML text input with CSS text-transform and JavaScript features

Similar Question: How to Convert a String into Pascal Case (UpperCamelCase) in JavaScript I am working on some basic tasks here, so please be patient. My current task involves using an XHTML text input to collect a user's name. I then display an ...

Is it possible to design a genuinely unique component with MUI?

Is it possible to create a custom MUI component called MyCustomButton that can be tailored using theme configurations, such as setting muiName = 'MyCustomButton'? The desired customization would involve defining styles for the root element and an ...

c# linq predicate

Two tables, TableEmployee and TableSal, have no relationship but I need to write a predicate using these two tables. TableEmployees: Contains Name and DepartmentId columns. TableSal: Contains Name, DepartmentId, and TotalSal. Question: I need to write a ...

Struggling to fix the "TypeError: not a function" issue

Hey everyone, I've been working on setting up an Express app to connect to mongodb using the node driver for mongodb. Unfortunately, I keep encountering a TypeError: mongodbconnect is not a function. I double-checked my export/import process and made ...

"Utilizing AngularJS to asynchronously send an HTTP POST request and dynamically update

I've been working on an angularjs chat module and have come across a challenge. I developed an algorithm that handles creating new chats, with the following steps: Click on the 'New Chat' button A list of available people to chat with wil ...

Tips for resolving the error message: React is not able to identify the `currentSlide` and `slideCount` prop on a DOM element

I recently implemented an image slider using "react-slick" in my next.js project. However, I encountered some warnings in the console related to the 'currentSlide' and 'slideCount' props on a DOM element. Warning: React does not recogni ...