Using Ajax to execute j_security_check operation

UPDATE: It seems like the culprit could be the URL. When using the login.html page, I observed the following log entry:

FINE: Security checking request POST /SesamaMaven/protected/admin/j_security_check

However, in the AJAX version, the log shows:

FINE: Security checking request POST /SesamaMaven/

I have configured authentication in Glassfish with JDBCRealm and it functions properly with a standard login.html form like this:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login Form</title>
</head>

<body>
<form method="post" action="j_security_check">
<p>You need to log in to access protected information.</p>
<table>
<tr>
  <td>User name:</td>
  <td><input type="text" name="j_username" /></td>
</tr>
<tr>
  <td>Password:</td>
  <td><input type="password" name="j_password" /></td>
</tr>
</table>
<p><input type="submit" value="Login" /></p>
</form>
</body>
</html>

My dilemma arises when attempting to implement the same functionality with AJAX, as it does not seem to work. Is there a way to resolve this issue?

HTML

<form class="navbar-form pull-right">
    <input class="span2" type="text" placeholder="Email" name="j_username" id="username">
    <input class="span2" type="password" placeholder="Password" name="j_password" id="password">
    <button type="button" class="btn" id="btnSignIn">Sign in</button>
</form>

JS

 $('#btnSignIn').click(function() {


$.ajax({
                type: "POST",
                contentType: "application/text",
                url: "j_security_check",
                // This is the type what you are waiting back from the server
                dataType: "text",
                async: false,
                crossDomain: false,
                data: {
                    j_username: "admin",
                    j_password: "paSSWORD"
                },
                success: function(data, textStatus, xhr) {
                    alert('Thanks for your signin in! ' + xhr.status);
                    window.location = "/SesamaMaven/protected/adminWelcome.html";
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log(textStatus, errorThrown);
                    window.location = "/SesamaMaven/index.html";
                    alert(' Error in signIn-process!! ' + textStatus);
                }


            });
        });

QUERIES

1) Is the correct contentType: "application/text" specified?

2) Should the URL tag be accurate or should I use action instead?

3) What about the parameters username and password in this scenario?

Glassfish attempts to authenticate but fails due to missing user and password details.

Answer №1

The issue lies with the contentType attribute being set to "application/text". After removing that line, I was able to resolve the problem.

However, there is still a lingering issue. In cases where authentication fails and it redirects to index.html, the page lacks CSS styling and the URL in the address bar remains as /protected/adminWelcome.html despite not successfully accessing that page.

Answer №2

After inserting the following code into my login.html file,

During the development phase, I found myself reluctant to manually enter my username and password every time.

xhttp.open("POST", "j_security_check", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("j_username=MY_USERNAME&j_password=MY_PASSWORD");
location.reload(true);

This code appears to notify users of incorrect login information.

In a similar scenario, I have two files named login.html and error-login.html,

with the only difference being that error-login.html contains the message "You have entered an incorrect username or password".

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 playing autoplay videos with muted audio

Is there a way to autoplay videos and mute the sound in Owl Carousel 2? Here is my code snippet - https://jsfiddle.net/ufqp8Lku/ $('.owl-carousel').owlCarousel({ items: 1, merge: true, loop: true, margin: 10, video: true, lazyLoad ...

Troubleshooting AJAX Post: Identifying the Issue with Variable Transmission

I am facing an issue with passing four variables via AJAX to be processed by PHP on the same page. The variables are newJudgeName, newJudgeSection, newJudgeStatus, and originalJudgeName. When I echo out the values in the success function, all values appear ...

Order the results by a predicate chosen by the user and a predefined secondary attribute

Trying to organize a table of results by a user selected criterion and then by a predefined secondary one. For instance, the ng-repeat setup looks like this: <tr ng-repeat="line in model.resultList | orderBy:['-predicate', 'secondary_va ...

Choose the data attributes you want to include and attach them to input elements using plain JavaScript

Creating a User Information form with a select element containing four options, each with data attributes. Under the select are input types to populate the data attributes when selected. Looking for help in achieving this using plain JS and onchange event. ...

Looking to retrieve country, state, city, and area based on inputting a pincode value using Node.js?

I'm currently working on a web project with nodeJs and ejs. I am looking for a solution that can automatically update the country, state, city, and area fields based on the input of a pin-code (zip-code). Are there any recommended packages in node js ...

Creating the greatest possible number using elements from an array in JavaScript

Given the array arr = [1,3,34,44,4,45,6,76,9,98,23], my goal is to create the largest possible number from those values. The output should be 99876645444343231. I attempted this with a solution that works well for two-digit numbers, but struggles with lar ...

Navigating through various locators with Protractor to fill an array

Currently utilizing protractor, my aim is to iterate through a collection of locators (each with unique identifiers) in order to retrieve the displayed text and then compare it against an array of expected values. I have encountered examples similar to th ...

Assign the JSON data to a variable

Can someone help me figure out how to save a JSON file from a URL in a variable and then work with it? Normally, it looks something like this: var jsonOriginal = { name: "Steve", age: 27, jobTitle: "Program Manager" }; alert(person.name); But now I need ...

Having trouble loading component parameters in Joomla 3.3 with AJAX?

I have created a basic component with certain parameters set in the component view. My goal is to load the menu item containing the component using AJAX. I initially referred to Chris Duell's tutorial on Ajax in Joomla with jQuery, which mentioned tha ...

Struggling to differentiate between the various CSS elements on a webpage and pinpointing the correct CSS for use

I have been attempting to replicate the "card-deck" layout that showcases eight cards on a specific webpage. After successfully copying the HTML structure by inspecting the card-deck class, I am now facing the challenge of locating the corresponding CSS ...

Learn how to evenly divide a circle based on the number of elements in an array using React, JavaScript, HTML, and CSS

Attempting to design a Polar/Radar Chart, my goal is to create distinct sections within the first circle based on the number of array items. Each item.name should be displayed in its own section with consistent text styling along the arc. The dimensions of ...

What is the best way to delete an HTML element created with JavaScript from the DOM?

After creating HTML markup using Javascript, I am facing an issue where I want to remove an element when clicked but it is not working properly. if (tBody) { return ( `<tr class="tr1"> <th ...

Create a library with CSS files added, excluding any test files

As I develop a React library, I've encountered an issue where the CSS files are being ignored during the build process. In an attempt to resolve this, I included the --copy-files flag in the build script, which successful copied the CSS files but also ...

Keep updating information dynamically using Ajax

I've set up a page featuring Bootstrap cards that fetch information from a MySQL database. What I'm Looking For I want these cards to refresh every 3 seconds without the need for page reload. I believe Ajax is the solution for this task as it a ...

The Perfect Scrollbar feature is not functioning properly in conjunction with the accordion menu

I am having some trouble with implementing the Perfect Scrollbar alongside an accordion slider menu. The scrollbar is not working as expected, and you can view the fiddle here. On initial page load, the scrollbar only appears for the first sub-menu aft ...

Check if the image source needs to be updated in case the image is not

There are two potential images that could be displayed. If the first one exists, it will be shown; if not, the second one will be displayed This code will appear on multiple pages, so in case the first image is missing, its source should be either "undefi ...

Ajax-powered Datatables

I am a beginner to data tables and I am attempting to retrieve data from a JSON text file (test1.txt). Below is an excerpt of the data present in the file, which contains over 5000 entries: [{"0":"22352442","ID":"22352442","1":"22126303","PARENT":"2212630 ...

"Vue's scope is always kept fresh and updated

Recently I've been working with a combination of vue.js and jquery. In my current scenario, I attempted to insert sidebar html code (containing vue syntax) into main.html using jquery. Unfortunately, upon injecting sidebar.html into main.html, vue.js ...

What is the correct method to display a THREE.Line in the correct sequence?

Currently, I am in the process of constructing a model solar system and have been using THREE.Line to create orbits for my planets. Everything seems to be going well until you view the orbits from the front of a planet, revealing that they are actually bei ...

How can you extract a property value from a nested object using JSON parsing?

Attempting to parse a property within nested objects and an array using JSON.parse(nodeInfluxSeries). Here's the structure: Array [ Object { "id": 1, "properties": Object { "nodeInfluxSeries": "[{&bs ...