Looking for an Ajax example demonstrating how to fetch a value from the server side on the client side without the need for a postback? Seek

I need to verify if a user is logged in using JavaScript when a button is clicked.

While I am aware that ajax can accomplish this task, I am unsure of where to begin and do not wish to delve into learning the entire ajax process.

Is there a straightforward code snippet that I could use as a reference?

==============================UPDATE 2===================================

After posting another question on this topic, I received an answer that might be helpful for others facing the same issue:

Can I return true to asp.net OnClientClick After an Ajax call? Or maybe some other way?

==============================UPDATE=====================================

Despite reading various examples, I have yet to find the specific one that I require. After receiving the server-side result, I am at a standstill. Below is my code - any assistance with the queries in the comments would be greatly appreciated. Thank you!

in .ascx:

<asp:Button ID="buttonSubmit" Text="Submit" OnClientClick="return buttonSubmitOnclick()" OnClick="buttonSubmit_Click" runat="server"/>

in .js:

function buttonSubmitOnclick() {
  showLogin();
  //What should I do here??? How do I return true if the ajax call returns 'true'?
  return true;  //???
}


//========== Ajax ==============

function showLogin() {
  var xmlhttp;

  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  }
  else {// code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        if (xmlhttp.responseText == "false") {
            $find('modalPopupLogin').show();  //Show Login Dialog
        };
    }
  }
  xmlhttp.open("GET", "AjaxService.aspx?t=auth", true);   //??? should the last parameter be "false"???
  xmlhttp.send();
}

Answer №1

If you're working with asp.net, one of the simplest ways to achieve this is by using page methods. These allow you to incorporate .NET code in your code behind and then access it through a javascript method. Keep in mind that the page method needs to be declared as static/shared since it will be used outside of the regular page life cycle.

Check out these examples for more information:
-
-

Calling Page Methods can be done easily, whether you choose to use jQuery or not.

Answer №2

There is valuable information on utilizing Ajax without jQuery at w3, including a practical example of ajax with asp at the end. It's a concise read that provides clear guidance.

After recent updates to the question: An explanation at the bottom discusses the distinctions between using asynchronous true and false.

When using async=true, the JavaScript doesn't wait for the response, so handling it 'here' may not be ideal:

function buttonSubmitOnclick() {
  showLogin();
  //What should go here??? How can we return true if the ajax call returns 'true'?
  return true;  //???
}

Upon executing xmlhttp.send(), JavaScript proceeds, exits out of showLogin(), and then exits out of buttonSubmitOnclick, irrespective of whether the login response has been received yet.

If async is set to true, you'll need to enhance the conditions in the onreadystatechange function to address cases where responseText equals "true".

xmlhttp.onreadystatechange = function () {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    if (xmlhttp.responseText == "false") {
      $find('modalPopupLogin').show();  //Display Login Dialog
    } else if (xmlhttp.responseText == "true") {
      //Proceed with the previous/submit action here because authentication has already occurred
    }
  }
}

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

How do I show a panel within another panel in ExtJS without it showing a blank screen?

Ext.define('something', { extend: 'Ext.panel.Panel', layout: 'border', constructor: function(config){ let me = this; me.callParent(arguments); me.initConfig(config); } }); If I define a cl ...

Error in Node.js: The res.send method is undefined

I'm having some issues with my first attempt at creating a simple Counter Strike API bot using nodeJS. The problem lies with the res.send function, as I keep getting an error message saying "res.send is not a function" every time I try to use it. Movi ...

Intersecting objects in three.js

While working on creating a surface with intersecting cubes, I noticed the current output. Unsure if this is the expected result given the stage of development in Three.js. In the dragable cubes example, everything seems to be functioning correctly. I&apo ...

Using Vue's $emit method within a Promise

I am currently working on an image upload feature that is based on a Promise. Within the "then" callback, I am attempting to $emit an event named 'success'. Although my VueDevTools shows me that the success event has been triggered, the associate ...

Sharing specific props with deeply nested components in React

I am experimenting with configuring props for children components. In this example, I am testing a function to target any child, whether nested or not, with the prop swipeMe. It works perfectly when the render function contains only a single child, like ...

What is the best way to ensure that any modifications made to an item in a table are appropriately synced

Utilizing xeditable.js, I am able to dynamically update the content of a cell within a table. My goal is to capture these changes and send them via an HTTP request (PUT) to the backend in order to update the database. Below is the table that can be edited ...

Showing submenu items in a jQuery menu system without causing the top level menu item to expand and fit

I currently have a menu system in place, which is quite simple, but there is an issue where the submenu items are larger than the top-level items. When hovering over the submenu items, the top-level menu expands to accommodate them. Is there a way to keep ...

Utilizing mixins with async components in VueJS

Currently, I am utilizing Webpack 2 to import components using a special syntax with require. Among the over 100 components available, only around 5-10 are used at any given time. These components share some common functionality such as props and lifecycl ...

How can I retrieve the reference number of an item by clicking a button within a list item in an unordered

Presented here is a collection of data points and a button nested within an ul <ul> <li class="mix" category-1="" data-value="600.35" style="display:block;"> <figure> <figcaption> <h3> ...

The attached zip file is not being successfully downloaded by the client

I'm facing an issue with downloading a zip file in my MERN application. Although I receive the file in the response, the client fails to initiate the actual download process. My approach involves zipping files using archiver and then fetching them. A ...

Setting up the default path that appears in the URL

Looking to simplify the URL path on your website? When developing webpages, you may have addresses like: www.example.com/index.html www.example.com/about_us.html www.example.com/en/index.html Is there a way to make these URLs more concise, such as: www ...

Updating parent scope data from within a directive without relying on isolated scope bindings

What is the best method for passing data back to the parent scope in AngularJS without using isolated scopes? Imagine I have a directive called x, and I want to access its value named a. The desired syntax would be: <x a="some.obj.myA"></x> c ...

I need to implement a div-based dropdown with a scrollbar in JavaScript and CSS to prevent it from extending beyond the screen. Additionally, the use of struts is essential in this implementation

Dealing with a dynamically populated div-based dropdown can be tricky, especially when it extends beyond the screen's limits and hides entries. This is an inherited application that lacks support, leaving me to handle it without the necessary expertis ...

Angular detects when a user scrolls on a webpage

I have developed a straightforward navigation system using Angular. The main controller is responsible for generating the menu. <nav class="{{active}}" ng-click= ""> <a href="#a" class="home" ng-click= "active='home'">Home< ...

The skybox in Three.JS is not appearing. Could there be an issue with the sizing or positioning?

Incorporating a small three.js scene into my project has been a challenge. I managed to create a skybox for the scene, but it's not appearing as expected. Interestingly, when I added a small box to the scene, it rendered perfectly. I suspect that the ...

Utilizing AJAX to send a parameter to PHP for processing

I am facing an issue with a script that is supposed to send data to a PHP file when a user clicks on an element, but unfortunately, it's not functioning correctly. Below is the jQuery code: jQuery( document ).ready(function( $ ) { $('.rve_b ...

A recursive approach for constructing a tree structure in Angular

Currently, I am working on a project involving the implementation of crud functions. To display the data in a tree-like structure, I am utilizing the org chart component from the PrimeNg library. The data obtained from the backend is in the form of an arra ...

When using ui-router in AngularJS, the page refuses to scroll to a specific ID if its hash is already present in the URL

Having trouble with hash-id linking using ui-router in AngularJS. When the URL already contains the desired hash (e.g., whatever.com/#/route1#des1) and an anchor tag with a link to #des1 is clicked, the link does not work and the page does not scroll down ...

Pausing briefly after selecting an element with Webdriver

I have been attempting to highlight an element on a webpage for a specific duration of time, approximately 5-6 seconds. However, I am facing difficulty in making the highlight persist for the desired duration as it currently flashes briefly. Despite using ...

Generate SVG components without displaying them

Is there a way to generate a custom SVG graphic through a function without the need to attach it to any element? Can I simply create an empty selection and return that instead? Here is my current implementation: function makeGraphic(svgParent) { retur ...