Refresh the controller variables displayed in the view

I'm currently working on a rails application and looking to refresh/reload the index method of my controller without refreshing the view. For example, here is my index method:

def index
    @title = params[:title]   
end 

And the corresponding html.erb:

<script>
function changeField() {
  var newTitle = "Alerts"
  $.ajax({
    url: 'index?title=' + newTitle,
    type: 'POST',
    contentType: 'application/json',
    data: '',
    dataType: 'script',
    headers: {
      'X-CSRF-Token': '<%= form_authenticity_token.to_s %>'
    },
  complete: function () {
    alert('<%=@title%>');
  }
  });
}
</script> 

<button type="button" onclick="changeField()"></button>

My issue lies in the fact that the @title variable on the view does not update, so I always see the original title instead of the new one.

Answer №1

As the page loads, the alert('<%=@title%>') displays 'first value'. However, once a new value is set, the JavaScript code cannot be reloaded. The HTML code only shows the first value and not the second.

To solve this issue, I recommend adding the following code to your controller:

respond_to do |format|
  format.html # index.html.erb
  format.js { render :json { :title => params['title'] || @title }.to_json }
end

Additionally, include the following in your JavaScript code:

success: function(data) { alert(data['title']) }

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

The parameters sent through Ajax are coming back as undefined

I'm encountering an issue where all the data passed in my Ajax call to a PHP function is showing up as "UNDEFINED" on the server side. The JQuery debugged fine, so it seems like the problem lies within the PHP side of things. $('.js-checkout-shi ...

Using PHP to decode a JSON array (Troubleshooting issues with Ajax JSON POST to PHP)

I am new to PHP and I have a jQuery/JavaScript based application that involves finding nearby places and presenting the results in a sorted order. I am attempting to move the sorting function from the HTML page to server-side PHP. This process includes ...

Using Postman to transmit a JSON API object

I'm currently utilizing the JSONAPI Specification from Here is an example of the data I have: { "data": { "type": "tag", "id": "1", "attributes": { "name": "Test" } } } Is there a way to send a post request to the e ...

Personalized Tumblr-style button

Hey there, I've been working on creating a custom Tumblr-like button and tried adding an iframe above it to make it clickable. However, something seems to be off as it's not functioning properly. I'm still trying to wrap my head around how i ...

Error in Vue class-based component: Unable to access property 'message' due to its value being null

I am currently exploring the combination of typescript and Vue for the first time in my project. I am encountering an issue that seems to be related to scope, but I could be mistaken. I referenced a small example from VueJS and adapted it as shown below: ...

Retrieving Information from JSON File Using a Variable (JavaScript/Discord.js)

While I was coding my Discord bot, I encountered an unexpected issue. Normally, after linking a JSON file, you can access data by using jsonFile.path to retrieve specific information. However, I faced a challenge where I needed to replace the path with a ...

To successfully use Router.use(), you must provide a valid middleware function. How can we resolve this issue of passing undefined as

I have developed a CRUD application using node.js and now I need to incorporate another node project as a microservice. To send HTTP requests to the other node project, I am utilizing the axios npm module. However, when I run the code, I keep encountering ...

The information is not appearing in the dropdown menu

The select tag for chapters is not displaying the result from the query properly. Instead of showing in the select tag, the chapter names are being displayed as echo statements. <!doctype html> <html> <head> <meta charset="utf-8"> ...

Ways to protect Ajax link requests

Picture this scenario: a user is trying to register on a website and is filling out a form. As the user fills in the form, jQuery continuously validates fields using regular expressions, checks if they are valid, etc. The email address serves as the prima ...

Mars Eclipse, AngularJS and the power of NodeJS

Could you please assist me in understanding the workings of node.js and angular.js within Eclipse? I am using Eclipse Mars and I would like to run my Angularjs project on a local server (localhost:8080) but I am unsure of how to accomplish this. I have a ...

Creating a custom route that is specific to a single ejs file

I'm trying to set up a URL like localhost:3000/hh234due with a unique ID that routes to a specific page. However, my current implementation is conflicting with other routes. How can I make the /:id route unique to one view? module.exports = fun ...

Include a Class into a label using jQuery

I am having an issue where I need to specifically add the error class to a <label> with the name attribute set to choice_16_0. However, when I try to achieve this using my code, it ends up changing all labels on the page to <label for="choice_16_0 ...

Locating a JSON object in Azure Data Factory using a specific string/value and then choosing a distinct value

I am currently working with a Legacy API that has no Dev support available. My task involves extracting data from this API. The data output I am dealing with is the result of activity().outputs.body.data { "column_id&qu ...

Retrieving information from dictionary in swift version 4

Currently, I am utilizing an API and trying to display its data in a table view. import UIKit import Alamofire class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOu ...

The authentication middleware is being executed for all routes within my app.js file, despite my intention to only apply it to a single route

I have developed a requireAuth middleware and integrated it into my app.js. In app.js, I have also imported all the routes from the routes folder. Each route.js file contains multiple chained routes. When I include the auth middleware in one of those files ...

Tips for temporarily preventing a digest cycle when modifying a scope variable

Is there a way to edit an array of objects in AngularJS, linked to the view through ng-repeat, without updating the scope until all objects have been modified? Consider this scenario: I need to update each object in the array and only then reflect the ch ...

Steps to open specifically the WhatsApp application upon clicking a hyperlink, image, or button

I need a code for my HTML website that will open the WhatsApp application when a user clicks on a link, image, or button while viewing the site on a mobile device. Only the WhatsApp application should be opened when a user interacts with a link on my webs ...

The GIPHY API object returns no results

Utilizing Angular 2 to fetch data from the GIPHY API. export class ListaGifsComponent { gifs : Object[] = []; urlBase = "http://api.giphy.com/v1/gifs/search?q="; termoPesquisado = "ryan+gosling"; key = "O8RhkTXfiSPmSCHosPAnhO70pdnHUiWn"; ...

Is there a way to verify the presence of a complete object by using a specific key in JavaScript

As I loop through my data, I only want to assign a random number to a fontObj if it is unique. A typical fontObj consists of: { postscript: "Calibri", style: "Bold", family: "Calibri" } In my code, I aim to iterate ...

What is the best way to structure files within the css and js folders after running the build command in Vue-cli?

Vue-cli typically generates files in the following structure: - dist -- demo.html -- style.css -- file.commom.js -- file.commom.js.map -- file.umd.js -- file.umd.js.map -- file.umd.min.js -- file.umd.min.js.map However, I prefer to organize them this way: ...