display rails view using ajax

I have developed a new form that I would like to render using ajax in case it fails validations.

In my controller, the code looks like this:

def create
  event = CEvent.new(params[:c_event])

  respond_to do |format|
    if event.save
      format.html { redirect_to admin_c_events_path }
    else
      format.js {redirect_to new_admin_c_event_path(:event => event.as_json, :errors => event.errors )}
    end
  end
end

The form has the parameter :remote => true, and when I submit the form by clicking on the button, the form is submitted via JavaScript but nothing gets rendered. However, when I reload the page, the required information renders correctly. If I reload the page again, an empty new form appears.

This is what my console output looks like:

Started GET "/admin/c_events/new?errors=%23%3CActiveModel%3A%3AErrors%3A0x007f74780d1d50%3E&event%5Babout%5D=&event%5Bbackground_content_type%5D=&event%5Bbackground_file_name%5D=&event%5Bbackground_file_size%5D=&event%5Bbackground_updated_at%5D=&event%5Bcontact_person_id%5D=11&event%5Bcreated_at%5D=&event%5Bfinish_at%5D=2014-01-13+11%3A19%3A00+UTC&event%5Bid%5D=&event%5Blocation%5D=&event%5Bname%5D=dewqr&event%5Bpress%5D=&event%5Bpress_contact_person_id%5D=11&event%5Bstart_at%5D=2014-01-13+11%3A19%3A00+UTC&event%5Bupdated_at%5D=&event%5Bvideo%5D=" for 127.0.0.1 at 2014-01-13 13:19:43 +0200
Processing by Admin::CEventsController#new as JS
  Parameters: {"errors"=>"#<ActiveModel::Errors:0x007f74780d1d50>", "event"=>{"about"=>"", "background_content_type"=>"", "background_file_name"=>"", "background_file_size"=>"", "background_updated_at"=>"", "contact_person_id"=>"11", "created_at"=>"", "finish_at"=>"2014-01-13 11:19:00 UTC", "id"=>"", "location"=>"", "name"=>"dewqr", "press"=>"", "press_contact_person_id"=>"11", "start_at"=>"2014-01-13 11:19:00 UTC", "updated_at"=>"", "video"=>""}}
  Person Load (1.2ms)  SELECT "people".* FROM "people" WHERE (p_type LIKE '%member%')
  Person Load (0.5ms)  SELECT "people".* FROM "people" WHERE (p_type LIKE '%mentor%')
  Rendered admin/c_events/_select_speakers.html.erb (4.0ms)
  Startup Load (0.4ms)  SELECT "startups".* FROM "startups" 
  Rendered admin/c_events/_select_startups.html.erb (4.6ms)
  Rendered admin/c_events/_schedule_fields.html.erb (13.8ms)
  CACHE (0.0ms)  SELECT "people".* FROM "people" WHERE (p_type LIKE '%member%')
  Rendered admin/c_events/new.html.erb within layouts/admin (116.0ms)
  Rendered layouts/_header.html.erb (3.3ms)
  Rendered admin/_top_bar.html.erb (4.8ms)
  Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 10216ms (Views: 180.0ms | ActiveRecord: 2.1ms)

Is there a way to render a view without reloading the page?

Answer №1

Hey there! This code snippet isn't your typical copy/paste solution, but it has always served me well.

Ensure you keep the remote: true in the form to trigger an ajax request and include format.js as a response in the controller's create action.

Application Controller


  ...
  after_filter :add_flash_to_header
  ...

  def add_flash_to_header
    # Only execute for Ajax requests.
    return unless request.xhr?

    # Add different flash messages to the header.
    response.headers['X-Flash-Error'] = flash[:error] unless flash[:error].blank?
    response.headers['X-Flash-Warning'] = flash[:warning] unless flash[:warning].blank?
    response.headers['X-Flash-Notice'] = flash[:notice] unless flash[:notice].blank?
    response.headers['X-Flash-Message'] = flash[:message] unless flash[:message].blank?

    # Ensure flash doesn't persist on subsequent pages.
    flash.discard
  end
  ...

create.js.erb

<% if @cevent.valid? %>
  $("#new_cevent")[0].reset();
  // Additional actions may be needed here
<% else %>
  $(document).find(".new_cevent").prepend("<%= j(render 'shared/error_messages', object: @cevent) %>");
<% end %>

Views/shared/_error_messages.html.erb

<% if object.errors.any? %>
  <div class="alert alert-danger alert-block">
    <h2><%= pluralize(object.errors.count, "error") %> prevented this schedule from being saved:</h2>
    <button type="button" class="close" data-dismiss="alert">x</button>
    <ul>
    <% object.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

Answer №2

simply substitute with this

format.js {render json: event}

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 properly panning across the canvas

I added event listeners to capture mouse movement, clicks, and releases in my code. canvas.addEventListener('mousemove', onMouseMove, false); canvas.addEventListener('mousedown', onMouseDown,false); canvas.addEventListener('mouseu ...

Retrieve documents from MongoDB database that have specific characteristics

Hello everyone, Today I'm trying to navigate mongoose queries. Imagine we have a collection like this: [ {letter: "A", name: "Books", action: "read"}, {letter: "B", name: "Notebook", action: &q ...

How can I make an HTML button function with a JavaScript script?

When I click a button in an HTML file, it should trigger a function in a JavaScript file to display an alert that says "hey." However, this simple task is not working for me and I am unsure why. Java Script is enabled in my browser (Google Chrome) and I am ...

Upon importing Chakra-UI in NextJS, the functionality may not work right away

Currently, I am diving into learning NextJS and Chakra-UI. Following the installation of Chakra-UI and attempting to import it, I encountered the error message shown below on the page. Any assistance in resolving this issue would be greatly appreciated. ...

Data loss occurs when the function malfunctions

Currently, I am working with Angular version 11. In my project, I am utilizing a function from a service to fetch data from an API and display it in a table that I created using the ng generate @angular/material:table command. Client Model export interfac ...

How can I remove the back button that the Ionic framework adds when using $state.go('app.home') to navigate to a page?

I have an app with a sidebar menu. Currently, I am on the second page and I am calling a controller function that redirects me to the first page using: $state.go('app.home'); The issue I am facing is that on this page, a back button is displayed ...

Error in hook order occurs when rendering various components

A discrepancy was encountered in React when attempting to render different components Warning: React has detected a change in the order of Hooks called by GenericDialog. This can result in bugs and errors if left unresolved. Previous render Next ren ...

What is the best way to store settings values permanently during the installation process in a react-native application?

I am looking for a way to save the settings of my app only during installation, rather than every time the app is opened, in order to prevent the options from resetting. I have tried searching on YouTube but most tutorials cover only user login persistence ...

Ensure that the HTML link is valid and authenticated using SESSIONS

When creating a website, one of the initial tasks I like to tackle is adding links at the bottom of the page for checking valid HTML and CSS: HTML5  •   CSS <div> <a href="http://validator.w3.org/check?uri=referer" ...

Is there a way to emulate synchronous behavior in JavaScript?

var routeSearch = new MyGlobal.findRoutes({ originPlaceId: search.placeInputIds.originPlaceId, destinationPlaceId: search.placeInputIds.destinationPlaceId, directionsService: search.directionsService, directionsDisplay: sear ...

Interactions between JavaScript and PHP scripts within a web application

THE SCENARIO In the midst of creating a web application that dynamically loads content by fetching data from a MongoDB database where items and their respective authors are stored in separate collections within the same database. The author's ID is s ...

Exploring the world of JavaScript by dynamically retrieving all class functions

Is there a way to retrieve an array of all functions from a given class, including functions inherited from parent classes? For instance: class Foo extends Bar { funcA() {} } class Bar { funcB() {} } const instanceFoo = new Foo(); getClass ...

Is it possible to implement a single lightbox modal that can display multiple images?

I am looking to create a fullscreen lightbox modal for multiple images, but I have been facing issues with finding the right solution. Most lightbox modals out there rely on jQuery and older versions of Bootstrap. Here is what I have tried so far: HTML: ...

Jade not binding correctly with Angular.ErrorMessage: Angular bindings are

Struggling with simple binding in Angular and Jade. I've tried moving JavaScript references to the end of the document based on advice from previous answers, but still no luck. Any ideas on what might be wrong? File: angular.jade extends layout blo ...

assigning a numerical value to a variable

Is there a way to create a function for a text box that only allows users to input numbers? I want an alert message to pop up if someone enters anything other than a number. The alert should say "must add a number" or something similar. And the catch is, w ...

What is the most effective method for verifying and cleansing email forms?

I have a form where I request information, but some fields like email are optional. If an email is provided, I want to validate and sanitize it before submission. Currently, my method only processes non-empty data. What is the best approach for thorough va ...

Having trouble with adding the copy to clipboard feature

I'm having trouble implementing a copy to clipboard option on my color selector. The goal is to display the selected color on an h3 tag and create a background color generator. Each time a color is chosen, it should appear on screen for us to easily c ...

Tips for creating a multi-tenant application using Node.js (express.js)

I need help finding information on developing a multi-tenant application using Node.js. Can anyone offer some guidance? Thank you. My technology stack includes: Node.js Express.js Mocha.js Postgres SQL JavaScript HTML5 ...

Before displaying the rows stored in the controller, ng-repeat initially displays one row

I am experiencing an issue with my back end service sending data to a $scope variable. I am using this variable to populate rows in a table with ng-repeat. Upon loading the page, initially one row is visible on the browser but then disappears once the loa ...

Is there a way to prevent an iframe from being recorded in Chrome's browsing history?

I'm in the process of developing a Chrome extension that inserts an Angular application into the user's browser window to create an interactive sidebar. I've been successful in most of my goals by inserting an iframe through a content script ...