Error messages in login form using AJAX in Rails

My issue seems to be quite complicated, but let's simplify it. I am working with devise and I need to display error messages below the form on my login page. Currently, when a user enters the wrong password, I see an error POST 401 (Unauthorized) in the console, but the errors are not showing up on the page.

slice_code.js.erb

$(document).ready(function() {
  var form = $('.centralized-login')
  form.submit( function(event) {
    event.preventDefault()
    var email = $('#email-input').val()
    var password = $('#password-input').val()
    var req = $.ajax('/user_role', {
    data: {
      email
    }
    })

    req.then( function(result) {
      var { role } = result
      switch (role) {
        case 'company_manager':
          $.ajax('/users/sign_in', {
            method: "POST",
            data: {
              "user[email]": email ,
              "user[password]": password,
              "authenticity_token": $('input[name="authenticity_token"]').val()
            },
            success: function(data, textStatus, req){
              window.location="/users/sign_in"
             }
            })
            break;

Do you think I should add something like $("ajax:error") ?

_new.html.erb

<div class="col-sm-8 col-md-6 col-xs-12">
  <div class="vr-textfield-wrapper">
    <%= f.email_field :email, id: "email-input", class: "vr-textfield", placeholder: t('users.passwords.new.email_placeholder'), required: true, aria_required: true, autofocus: true %>
    <span class="vr-field__invalid-msg"><%= t 'users.passwords.new.valid_email'%></span>

    <% if resource.errors.full_messages_for(:email).first %>
      <div class="vr-textfield-wrapper">
        <div class="alert alert-danger">
          <div class="error-explanation">
            <%= t('activerecord.errors.models.user.attributes.email.not_found_in_database') %>
          </div>
        </div>
      </div>
    <% end %>
  </div>
</div>

Edit

        success: function(data, textStatus, req){
          window.location="/users/sign_in"
        },
        error: function (jqXHR, textStatus, errorThrown) {
          $('.centralized-login').find('.error-explanation').html(errorThrown)
          console.log(textStatus + " " + errorThrown);
        }
        })

sessions_controller.rb

class Users::SessionsController < Devise::SessionsController
  include LogoutUsergroups

  def after_sign_out_path_for(_user)
    new_user_session_path
  end
end

Answer №1

To display the error in the JavaScript response (create.js.erb) within the view file itself, you can follow something similar to the example below:

<%- if resource.errors.any? %>
   var id = $('form#Id') <!-- Replace with your selector -->
   <% resource.errors.each do |key, value| %>
     id.find('selector').html("<%= "#{key.to_s.humanize} #{value}" %>");
   <% end %>
<%- end %>

Alternatively, you can utilize an error function similar to the success function, like this:

$.ajax({
         success: function(data, textStatus, req){
          window.location="/users/sign_in"
         }           

         error: function (jqXHR, textStatus, errorThrown) {
             id.find('selector').html(""); # Use the error here to display in the UI.
             console.log(textStatus + " " + errorThrown);
         }
      });

The $("ajax:error") should be implemented when using remote: true for form submission. For more information, refer to: https://github.com/rails/jquery-ujs/wiki/ajax

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

Vue event manager, accessible for all components

I have created a new Vue instance and assigned it to the window object, thinking that it would be accessible throughout all components. I expected this setup to allow me access to events emitted anywhere within my application. However, it seems like this ...

What happens when the loading state does not update while using an async function in an onClick event?

I'm currently working on implementing the MUI Loading Button and encountering an issue with changing the loading state of the button upon click. Despite setting the state of downloadLoading to true in the onClick event, it always returns false. The p ...

Efficiently sending data to Service Bus from an HTTP-triggered function

How can I link the output to service bus? I've configured an out binding in my Azure function: { "queueName": "testqueue", "connection": "MyServiceBusConnection", "name": "myQueueItem", "type": "serviceBus", "direction": "out" } I started ...

Verify the Absence of an Internet Connection Through a Popup on a Windows 10 Application Developed in Javascript

Hey there, I've been browsing the web but can't seem to find a comprehensive tutorial on how to write a code that displays an error message when there is no internet connection. I'm currently using Visual Studio to develop a Windows 10 App w ...

Display the download link once the user has submitted their email address. Utilize PHP and AJAX for

We are providing software downloads to our valued users. After a user submits their email address, we would like to display the download link using Ajax for a seamless experience. Additionally, the email addresses will be sent directly to iContact for fur ...

Is it a poor practice to combine jQuery's $.each with an AJAX request?

Here is the code snippet that I am working with: $(document).ready(function() { var url = "https://graph.facebook.com/search?q=cinema&type=post"; $.ajax({ type: "POST", url: url, dataType: "jsonp", success: fun ...

Here is a helpful guide on updating dropdown values in real time by retrieving data from an SQL database

This feature allows users to select a package category from a dropdown menu. For example, selecting "Unifi" will display only Unifi packages, while selecting "Streamyx" will show only Streamyx packages. However, if I first select Unifi and then change to S ...

Encounter an Internal Server Error while using Laravel 5.4

I am encountering an issue while attempting to implement ajax search in my laravel project. I have included the controller and JavaScript code related to this problem below. Can you please take a look and let me know what may be causing the error? pu ...

What is the best way to utilize useEffect solely when the length of an array has

Is there a way to trigger a state update only when the length of the prop "columns" changes? useEffect(() => { if (columns.length !== prevColumns.length) { // update state } }, [columns]); Any suggestions on how to achieve this? ...

Transferring an array from PHP to jQuery through the use of AJAX

My JavaScript code communicates with a PHP page to retrieve data from a database and store it in an array. Now, I would like to use jQuery to loop through that array. This is how the array is structured: Array ( [0] => Array ( [image] => articl ...

Error: The hook call is invalid and can only be made within the body of a function component in ReactJS

Hello everyone, I am currently facing an issue with saving the lat and lng variables in the state within a hook. When trying to do so, I encounter the following error message: "Error: Invalid hook call. Hooks can only be called inside the body of a functio ...

Using Button Elements to Initiate Server Requests in Node.js

I'm currently in the process of designing a menu for my Node JS application and I'm struggling to find a way to send server requests without relying on the browser's navigation bar. Here is how my directory structure is organized: /applica ...

Update the link by simply clicking on a div tag

I am currently working on a PHP page and my goal is to add the extension ?id=variable_value to its URL when I click on a specific div. However, whenever I try to do this, it shows me an error message stating that the URL with the extension is undefined. B ...

Attempting to reduce the width of the dig when it reaches 400

I have a square element with a click event that increases its size by 50 pixels on each click. However, once it reaches a size of 400 pixels, the size decreases by 50 pixels with every click instead. Additionally, when the size of the square reaches 100 p ...

Tips for setting up a select dropdown in AngularJS using ng-options when the value is an object

How can I set the initial selection of a select field using ng-options? Consider the items we have: $scope.items = [{ id: 1, label: 'aLabel', subItem: { name: 'aSubItem' } }, { id: 2, label: 'bLabel', subItem: { ...

retrieving information from the database and passing it to the controller

I'm in the process of developing a new API with Express, following the MVC architecture. However, I've been facing difficulties getting the data to successfully return from the database access file to the controllers file. Initially, I attempted ...

Using the same component multiple times within a parent component in Angular 2

I have a CarsComponent where I repeatedly use the ChartComponent in its template, as shown in the code snippet below: cars.component.html: <div class="row" *ngIf="selectedItemId"> <div class="col-12 mb-2&quo ...

What is the best way to ensure a toggle button retains its state when navigating between different React Routes

I've been working on implementing a dark mode toggle in JavaScript using React. I'm utilizing Material-UI for my page design and I've successfully made the button switch the theme of the entire page upon clicking. However, I've encounte ...

Assurance-driven number tally

I'm diving into JavaScript and recently started exploring promises. I've put together a code snippet that logs the value passed to the promise function as a parameter after the setTimeout function is triggered. Now, I'm wondering if there&ap ...

Having trouble getting webpack to transpile typescript to ES5?

Despite following official guides and various tutorials, I am still facing an issue with compiling my code to ES5 using TypeScript and webpack. The problem is that the final bundle.js file always contains arrow functions. Here is a snippet from my webpack ...