Updating a Rails partial using JSON response from an AJAX post request

I recently implemented an AJAX post request in my backend Rails application to upload a file. Upon successful posting, the response contains a JSON list of files.

Now, I face the challenge of reloading the file list on my 'detalhes.html.erb' view page, which displays the list as a partial.

Below is my controller method:

  def upload_arquivo
    @ponto_venda = PontoVenda.find(params[:pv_id])
    nome = params[:key].split('/').last
    @arquivo = Arquivo.new(nome: nome, endereco: params[:url], s3_key: params[:key], tamanho: params[:tam], user_id: params[:u_id], tag_id: params[:tag])
    if @arquivo.save!
      ArquivoPontoVenda.create(arquivo_id: @arquivo.id, ponto_venda_id: @ponto_venda.id, fachada: false)
      response = { files: filtro_pv_arquivos, message: "O arquivo '#{nome}' foi salvo" }
    else
      response = { files: '', message: 'Ocorreu um erro ao salvar o arquivo, por favor, tente novamente' }
    end
    render json: response
  end

And here's my AJAX post method at _arquivos_upload.html.erb:

$.ajax({
    url: 'some_url',
    type: 'post', processData: false
})
.success(function(data) {
    console.log(data.files.length);
    // attempting to reload the partial after the POST request
    $('#display-arquivos').html("<%= escape_javascript(render 'arquivos_buscados') %>");
});

The data.files contain the correct information, but I'm struggling to pass it to the rendered partial. Can someone suggest a better way to handle this?

Here's where I render the partial detalhes.html.erb:

<div class="card" id="display-arquivos">
    <%= render 'arquivos_buscados' %>    
</div>

I have already explored various solutions including:

github link

setting .html(data.files)

using js.erb file logic

Answer №1

Your work is looking really nice. You might want to consider updating your partial to accept a local variable and then passing it explicitly when rendering the partial.

<div class="card" id="display-arquivos">
    <%= render "arquivos_buscados", locals { files: @files #add this } %>    
</div>

$('#display-arquivos').html("<%= escape_javascript(render "arquivos_buscados", locals: { files : data.files } ) %>");

Answer №2

In my opinion, it would be better to return html rather than json. After that, in the .success function of the ajax method, you can simply use:

$.ajax({
  url: 'some_url,
  type: 'post', processData: false
})
.success(function(data) {
  $('#display-arquivos').html(data);
});

You may need to modify your controller action as follows:

def upload_arquivo

  ...

  if @arquivo.save!
    ArquivoPontoVenda.create(arquivo_id: @arquivo.id, ponto_venda_id: @ponto_venda.id, fachada: false)
    @files = #populate your @files variable
    render "arquivos_buscados"
  else
    render :something_else
  end

end

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

Utilizing Ajax for submitting data in a Spring application

I'm attempting to send a PUT request to the controller using AJAX. Here is my code: $().ready(function(){ $('#submit').click(function(){ var toUrl = '/users/' + $('#id').val() + '/profile'; ...

Resolving CORS Issue with Passport in Node.js

I have exhausted all efforts to integrate passport into my application without success. Every login attempt with various providers (Facebook, Google, Twitter, Microsoft) has resulted in an error message similar to this: XMLHttpRequest cannot load https:// ...

When trying to use bootbox.confirm within a dynamically loaded AJAX div, the modal unexpectedly opens and

I have implemented bootbox into my project, which was downloaded from . user_update.php is being loaded in a div within users.php using ajax functionality. Within user_update.php, there is a JavaScript function called validateForm(). Right after the functi ...

Using various hues for segmented lines on ChartJS

I am working with a time line chart type and I want to assign colors to each step between two dots based on the values in my dataset object. In my dataset data array, I have added a third item that will determine the color (if < 30 ==> green / >3 ...

Exploring a multitude of data within a hefty json log document using node.js

I am dealing with a JSON file named sensorlogs.json that contains data from different sensors transmitting at varying frequencies. The timestamps in the file are not in order and one sensor may have missing entries. The goal is to analyze each sensor&apos ...

How can I dynamically change the default value of the selected option dropdown in React-Select when a new option is chosen?

Can you help me understand how to update the default displayed value on a dropdown in a react-select component? When I choose a different option from one dropdown, the select dropdown value does not change. I've attempted this.defaultValue = option.va ...

"Exploring the world of Typescript's return statements and the

I'm currently grappling with a design dilemma in typescript. Within my controller, I perform a validation process that can either return a 422 response, which ends the thread, or a validated data object that needs to be utilized further. Here's a ...

Utilize getJSON to refresh the JavaScript datetimepicker

I am currently using an api with ajax (getJSON) to append data to a specific div called 'open' on my website. However, I now want to update the static values in my datetime picker script for minTime and maxTime. Here is the code snippet: AJAX ...

Iterating through a collection of items in Vue.js using the v

I am attempting to cycle through an object using v-for. exampleObject =[a,b,c,d] Requirement = display only a if it exists in exampleObject, otherwise show b, c, d. <div v-if="checklist.types"> <div v-for="type in checklist.t ...

Setting up a Vue 3 parent component to emit events to a child component: a step-by-step guide

Seeking assistance with setting up a Vue 3 Tailwind parent component button to trigger a HeadlessUI transition event in a child component. The objective is for the button in the parent to emit an event, which the child will then watch for before triggering ...

What is the best method for uploading and saving a file using AngularJS and ExpressJS together?

I am using a library for AngularJS called angular-file-upload. Despite successfully setting it up and getting image uploads to work, I am facing an issue with passing the file to the server side (express js). Jade: input.form-input(ng-model="userAvatarFi ...

Freezing objects using Object.freeze and utilizing array notation within objects

Could someone kindly explain to me how this function operates? Does [taskTypes.wind.printer_3d] serve as a method for defining an object's property? Is ["windFarm"] considered an array containing just one item? Deciphering another person& ...

Enhancing interactivity: Implementing a ripple effect for Card clicks in Material UI

I'm curious if there's a method to incorporate a ripple effect into Material UI's Card component when it is clicked. Additionally, I am wondering if it is achievable to have the ripple effect display on top of the content within the Card co ...

SyntaxError: Unexpected token : error caused by an invalid label

When attempting to perform an ajax call, I receive a JSON object as a response: { id: 6, success: "true" } The ajax call in question is the following: window.foobar = function(foo){ $.ajax({ url: "http://foobar.com/sites/foo/", ...

Activate the default JavaScript action within an event handler

I need help understanding how to initiate the default action before another process takes place. More specifically, when utilizing a third-party library and applying an event handler that triggers one of their functions, it seems to interfere with the defa ...

Using raphaeljs and freetransform in conjunction with clip-path

Currently, I am utilizing Raphael along with Elberts FreeTransform Plugin. You can view my progress so far by visiting MyWork The issue arises when I attempt to translate or rotate the set of rectangles within my clip path. Once rotated or translated, it ...

Ways to implement a scrollable v-list component using Vuetify

I have set up a v-list using flex layout, where the v-list expands to fill the remaining space horizontally in a column. However, if the list contains many elements with a total height that exceeds the column's height, the list ends up sticking out of ...

Troubleshooting CSS Hover Not Displaying Properly in Angular 14

In the footer class of my HTML, there is a code snippet with chevrons: <div class="link-list"> <div *ngFor="let link of insideLinksLeft | originalOrderKeyValue" class="link"> <a [href]="link.val ...

What is the best way to remove text messages from a channel that only allows images?

I have developed a Discord bot named YES with a specific text channel for images only. My goal is to program the bot to automatically delete any text messages in this channel and respond with "You cannot send text messages." However, I also want to create ...

Add a class individually for each element when the mouse enters the event

How can I apply the (.fill) class to each child element when hovering over them individually? I tried writing this code in TypeScript and added a mouseenter event, but upon opening the file, the .fill class is already applied to all elements. Why is this ...