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

Exploring the Magic of Class Variable Destructuring in React

Is there a simpler method to break down a prop object and assign them to variables of the same name in the class? I am familiar with ({ first: this.first, second: this.second, } = props) however, it can get complicated when dealing with numerous variable ...

Encountering Problem with Jmeter Script Playback - Kindly Activate JavaScript to Access Page Information

I'm currently experiencing a challenge when trying to simulate the following scenario in my JMeter script. I would truly appreciate any assistance or solutions you can offer. My goal is to create a JMeter script for a form submission process within a ...

The error message "Uncaught ReferenceError: require is not defined" is commonly encountered when using Webpack

Despite countless similar questions, none have provided a solution to my issue because the underlying problem seems to elude me. I am attempting to bundle files for the browser using webpack 4.26.1, but no matter what I try, I consistently encounter the er ...

Encountering difficulties setting cookies within the app router in Next.js

I've been diving into next.js and I'm trying to figure out how to set a cookie using the code below. However, I'm encountering an error: "Unhandled Runtime Error. Error: Cookies can only be modified in a Server Action or Route Handler." I ...

execute an ASPX.VB function using AJAX

Here is my query: I am trying to invoke a specific method from the code-behind file of an asp.net webform. Below is my jQuery (Ajax) function: function LoadPayments(_page) { var cliente = 245328; $.ajax({ type: "POST", url: "Pay ...

Material UI - Exploring the Tree View Component

Seeking advice on structuring server data for utilization with the TreeView component from Material UI: https://material-ui.com/api/tree-view/ I need to efficiently handle large datasets by fetching child nodes dynamically from the server upon user intera ...

Stripping away HTML tags from a JSON output

I'm attempting to retrieve a JSON result using jQuery. $.ajax({ type: "GET", url: "http://localhost:8080/App/QueryString.jsp?Query="+query, contentType:"text/html; charset=utf-8", dataType: "json", success: function(json) { if(data!="") ...

Eliminate server-side functionality from the React project's boilerplate template

After cloning and installing the project from https://github.com/react-boilerplate/react-boilerplate, I realized that I only need the client-side portion as I intend to use a pre-existing server (express) for my application setup. Below is an excerpt f ...

Using AJAX to send an array as a response from Laravel

After implementing Laravel to handle an AJAX post request, I encountered an issue with displaying the route data. public function infoRoute(Request $request) { // Extracting required information $ship_id = $request->ship_id; ...

Tips for positioning two elements side by side on a small screen using the Bootstrap framework

Greetings! As a beginner, I must apologize for the lack of finesse in my code. Currently, I am facing an issue with the positioning of my name (Tristen Roth) and the navbar-toggler-icon on xs viewports. They are appearing on separate lines vertically, lea ...

Issues with $.post function causing HTML to be displayed instead of the intended value

I have a question about sending the value of an HTML element to the server using POST. When I alert the result, I expect to only see the value but I am also getting the HTML content of the PHP file included in my code. Why is this happening? function post ...

Can React Router be integrated with Material UI tabs?

I have made some changes to the code of the Tabs component in material ui, <AppBar position="static"> <Tabs variant="fullWidth" value={value} onChange={handleChange} aria-label="nav tabs example" > < ...

Is there a way to adjust the text color of a label for a disabled input HTML element?

If the custom-switch is active: the label text color will be green. If the custom-switch is inactive: the label text color will be red. A JavaScript (JQuery) method call can be used to activate one button while deactivating another. The Issue It appe ...

Guide on dynamically updating a div in PHP with a mix of text output and images at regular intervals

My current project involves creating a browser-based card game primarily using PHP, with potentially incorporating other languages to help me enhance and test my PHP skills. However, I've encountered difficulties while attempting to implement various ...

The font remains the same despite the <Div style=> tag

I have a script that loads external HTML files, but I am facing an issue with changing the font to Arial. The script is as follows: <script type="text/javascript"> $(document).ready(function(){ $("#page1").click(function(){ ...

Clearing the filename in a file type input field using React

When using this input field, only video files are accepted. If any other types of files are uploaded by enabling the "all files" option, an alert will be displayed. While this functionality is working correctly, a problem arises if a non-video file is adde ...

Utilizing a TypeScript definition file (.d.ts) for typings in JavaScript code does not provide alerts for errors regarding primitive types

In my JavaScript component, I have a simple exporting statement: ./component/index.js : export const t = 'string value'; This component also has a TypeScript definition file: ./component/index.d.ts : export const t: number; A very basic Typ ...

The calculator I designed using HTML, CSS, and JavaScript is experiencing difficulty adjusting to various screen sizes

I recently built a calculator using HTML, CSS, and JavaScript. It works perfectly on PC or big screens, but when viewed on smaller devices like phones or tablets, the display gets cut off and does not adjust properly. Here are some example pictures for ref ...

Trouble accessing account using OOP PHP (Prepared Statement)

Recently, I've encountered some challenges while developing a Login System using OOP PHP with Prepared Statements. Even after correctly entering the username and password, the system still identifies them as incorrect. Below is the code snippet I&apos ...

JavaScript and Responsive Design Techniques

I'm struggling to create a responsive page that starts with a mobile-first approach, but I keep running into the same issue. When I have my dropdown menu in the mobile version, it looks good. However, when I try to switch it to the non-mobile version ...