Enhancing the model in Rails 5 using Ajax and dynamically inserting the HTML response into the view

I am currently calling the update action of the User controller using a form with remote: true. I would like to display the updated user HTML in the view, so I have included this code in the controller:

def update
  @user = User.find(params[:id])
  respond_to do |format|
    if @user.update_attributes(user_params)
      format.html {
        flash[:success] = "Profile updated"
        redirect_back fallback_location: @user
      }
      format.js { render partial: 'user', locals: { user: @user } }
    else
      format.html { render 'show' }
      format.js {}
    end
  end
end

Everything seems fine, as the server replies with the correct rendered HTML and status 200. However, I am encountering an issue with my CoffeeScript:

$ ->
  $(".edit_user[data-remote]").on "ajax:success", (e, data, status, xhr) ->
    console.log(e)
    console.log(data)
    console.log(status)
    console.log(xhr)
    $(this).closest('tr').fadeOut()
    if $(this).data('action') == 'hire'
      $('#active-users').append data
    else
      $('#archive-users').append data

This piece of code is not running, and I cannot figure out why. I noticed that when I remove

render partial: 'user', locals: { user: @user }
from the controller, the CoffeeScript works (though I require the rendered HTML).

Is there a way to adjust my CoffeeScript for it to function correctly? I am relatively new to JS and CoffeeScript.

Answer №1

By using the 'remote: true' attribute, the Javascript file associated with the controller action, in this case 'update' will be automatically executed. There is no longer a need to bind a separate file for ajax:success or any other similar event.

So, start by modifying:

format.js { render partial: 'user', locals: { user: @user } }

To:

format.js {}

Next, create a new file named update.js.erb within the views/user directory, and include the following content:

$('#active-users').append('<%= j render partial: 'user', locals: { user: @user } %>')

The purpose of using 'j' here is to escape the HTML output ensuring that the Javascript does not encounter an error. Once the controller action is completed, the contents of the partial will be appended to #active-users. Additionally, you can include any additional required Javascript code within this file as well.

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

Unfortunately, bower-rails is no longer able to install any packages

For some unknown reason, a current project installed with bower-rails cannot perform bower:install anymore! Even though it was working previously and I already have packages installed locally, now I am experiencing issues. No changes have been made! I at ...

The execution of dynamically generated Javascript in JSON format, returned through AJAX, is prevented when it is appended

Recently, I encountered an issue on my webpage where I made an AJAX request to a PHP script. The PHP script responded with a valid JSON object and set the Content-type header to application/json. After examining the JSON format using console.log(JSON.stri ...

Rearrange the positioning of jQuery DataTables sort icons to display them below the original text

After meticulously inspecting all of my CSS files, even the abundance of them, along with thoroughly examining and eliminating the sDom configurations for my jquery Datatables plugin, I cannot fathom why the positioning of the sort icon (the captivating up ...

The function does not generate an image, but it will display the one that is

It looks like there may be an issue within the function that is preventing the image from being created, or possibly in the script itself which is not passing the image to the function properly. Below is the upload script (please note: this script is inje ...

Go back to the top by clicking on the image

Can you help me with a quick query? Is it feasible to automatically scroll back to the top after clicking on an image that serves as a reference to jQuery content? For instance, if I select an image in the "Portfolio" section of , I would like to be tak ...

Tips for refreshing an html table without affecting the scroll location?

HTML: <div class="html_table"></div> # Within the html body tag. Utilizing Ajax function to retrieve table data. var $html_table= $('.html_table'); function ajaxCallFunction() { $.ajax({ type: 'POST', ...

Mastering the extraction of key/value pairs from a JSON response in the OnComplete ajax

After executing a specific action, it is returning the following outcome: return Json(new { result = true, value = "hello" }, "text/html"); I'm wondering how can I retrieve the value in my onComplete function? onComplete: function (file, respo ...

Flask and the steps to modify CORS header

While working on my localhost, I came across a CORS error when building an application to handle search queries for a different domain. The specific error was: "Cross Origin Request Blocked... (Reason: CORS header 'Access-Control-Allow-Origin' mi ...

Failed to input data into MySQL database's dynamic field

I have encountered an issue while trying to enter dynamic fields into a MySQL database, and I am struggling to figure out the cause of the problem. Below are both the HTML and PHP files provided; I would greatly appreciate any assistance in identifying and ...

Center the first column in jQuery Datatables

Looking to center-align only the first column named "Status": $("#TransactionTable").DataTable({ ajax: { url: '/Transaction/SearchMockup', type: 'POST', data: { ...

Retrieve a DOCX file via AJAX response

I am encountering an issue with a Django function that returns a file: ... return FileResponse(open('demo.docx', 'rb')) I am using ajax to fetch it on the client side. Now, I need to download it on the client side. This is the code I a ...

Choose the DIV element based on its data attribute using JSON

When using each(), my goal is to: Hide all divs where the data-infos.grpid = $jQuery(this).data('infos').grpid Show the next div where data-infos.ordre = $jQuery(this).data('infos').next_ordre I am unsure how to apply a "where" ...

Make sure to refresh the model using an Ajax request in Spring MVC

I have a page where I use AJAX to insert data into my database. On that same page, I display a table of records that are inserted. Each time I add a new record, I want to update the content of the table. Here is what I have implemented: @RequestMapping(va ...

The contents within the div element exceed the width of its parent element

Hey there, I'm currently working on a Rails application to showcase some links in a horizontal layout. The links are indeed displaying horizontally without wrapping, just as intended. However, I've noticed that the containing div is wider than th ...

Jquery problem: dealing with empty spaces

I am working on a project where I need to use jQuery to disable specific input fields, like the following: $("input[value=" + resultId[i].name + "]" ).prop('disabled', true); $("input[value=" + resultId[i].name + "]" ).css({ 'background-col ...

Retrieve the element that is currently being hovered over within the same nested selector

I am facing a challenge in selecting the currently hovered element with a nested selector. The ".frmElement" class is used as the selector. When I hover over the ".frmElement" element at a certain level, all the previous selector elements display the hover ...

Issue with disabling checkboxes in jsTree

Currently utilizing the latest version of jsTree in one of my applications. I would like to have specific checkboxes disabled by default. To achieve this, I am referencing this resource. The jstree code I am using is as follows: $("#"+"div_"+aspectid).js ...

How can you use a jQuery Selector to target all images and sources within dynamic containers?

I am currently attempting to identify all images and their paths (srcs) within the dynamic containers. The dynamic containers refer to container patterns stored in an array, which is filled dynamically. For example: var containers = new Array( ...

Utilize jQuery to showcase images on your webpage

There seems to be an issue with image display - sometimes the selected image does not show up until clicked a second time. Using jQuery $('#morefiles').change(function (event) { if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test($(this).val())) { ...

Bar Chart Data Label Problem with HighCharts

My goal is to have the label positioned outside the bar stack. I attempted to achieve this using the code below, but it seems to be inconsistent in its results. dataLabels: { enabled: true, color: '#333', ...