Is it possible to generate a post automatically every second using an AJAX call, with no user input required?


Want to find the answer? Check out this link:

Render a view in rails via AJAX and controller


In my Rails application, I have a Post model that automatically creates and saves new posts while deleting old ones every 10 seconds using an AJAX call set within a setInterval() function in my application.js file:

var post_value = 0;
setInterval(function(){

        $.get('https://api.test', function(data){
            post_value = data.result.c[0];
        });

        $.ajax({
          type: "POST",
          url: "/posts",
          data: { parameter: post_value }
        });

    }, 1000);

The AJAX calls work smoothly saving new posts and deleting old ones. Here is the corresponding controller code:

  def index
    @posts = Post.all
    @bet_last = Bet.last
  end

  def create
    @post = Post.new
    @post.value = params["parameter"]
    @post.save  
    Post.first.destroy

    @last_post = Post.last
    @posts = Post.all

    render "index"

  end

Below you can see the template HTML view (index.html.erb) for displaying the posts dynamically:

<% @posts.each do |p|%>
    <tr>
        <th scope="row"><%= p.id%></th>
        <td>...</td>
        <td><%= p.value%></td>
        <td>Active</td>
    </tr>
<%end%>

I am facing challenges in updating the page dynamically without refreshing it when new posts are added or deleted. Any suggestions on how to achieve this?

Thank you for your assistance.

EDIT:

Using the following render statement in the controller instead of render "index" seems to solve the issue:

render :js => "window.location = '#{root_path}'"

However, this approach causes the page to reload, which is not the desired outcome.

Answer №1

Make sure to include a success callback in your ajax call to dynamically update your HTML content.

$.ajax({
      type: "POST",
      url: "/posts",
      data: { parameter: post_value },
success: function(data){
// Use this callback function to update your HTML content
}

    });

Answer №2

After gaining a clearer understanding, I have opened another question that is much improved from my previous one. And guess what? It's already solved! :-)

Check out my updated question about rendering views in Rails via AJAX and controller

I was struggling with understanding how to do the rendering in my controller:

def create
  # your logic here 
  render json: @bet

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

Having trouble viewing the npm version on Ubuntu due to the error message: "Module 'semver' not found"

After reinstalling ubuntu on my computer, I proceeded to install node, react, and npm. However, when I attempted to run an old project, I encountered the same error message that I had faced previously. Even checking the version of npm resulted in an error. ...

Steps to partially open the Modal Sheet Swipe Step by default

I've set up a modal sheet component with the following structure: <f7-sheet class="myClass" style="height: auto" swipe-to-step :backdrop="false" > <div class="sheet- ...

What causes a significant influx of packages each time I execute the command `npm install`?

https://i.sstatic.net/a3BxV.png https://i.sstatic.net/dcVXS.png Could this be related to my overall package.json file? ...

Real-time collaborative Whiteboard using WebSocket technology (socket.io)

I am currently working on developing a collaborative online whiteboard application using HTML5 canvas, Node.js, and Websockets (Socket.io). While my progress is going well, I am facing some challenges when it comes to drawing circles. I have been successfu ...

Refresh React Components on the Fly (Solr)

I am relatively new to ReactJS In my React class, I have a function that is rendering multiple items: (Sample) var app = app || {}; app.Results = React.createClass({ componentDidMount: function () { }, handleUpdateEvent: function(id) ...

Update the image within the svg tag

I am attempting to modify a preexisting SVG element within an HTML document. Here is the current code: <svg class="logo" viewBox="0 0 435 67"> <!-- IMAGE DIMENSIONS --> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#logo- ...

Enhancing User Experience with React-Redux: Implementing Subcategory Visibility based on Main Category Selection

How can I implement action logic to show and hide elements based on user interaction with main categories? Currently, all subcategories are being displayed at once, but I want them to be shown only when a user clicks on the corresponding main category. For ...

Having trouble retrieving JavaScript data sent via AJAX using the Playframework2 DynamicForm object. encountering an error: `{data[undefined]=}`

When I send a Javascript array via Ajax using the POST method like this: $.post(assignmentsubmitAddress, submittedUnitsArray, I receive a Status OK response. However, when I try to retrieve that data on the server using the Play Framework 2 Dynamic form ...

Resize a group of images to match the parent's width and height dimensions

I am working with a div that contains variously-sized images and is nested inside a parent container. <div id="parentContainer"> <div id="boxToScale"> <img src="http://placehold.it/350x150" /> <img src="http://placehold.it/150 ...

When attempting to extract values from selected items in Nextjs, clicking to handle them resulted in no action

I am facing an issue with my Nextjs project. I am trying to gather values from select items and combine them into a single object that needs to be processed by an API. However, when I click the select button, nothing happens. How can I resolve this issue? ...

I'm looking to add a next and previous button within my jumbotron- can anyone offer guidance?

As I near the completion of my Full Stack Nanodegree final project and await assistance from my instructor, I've taken on the task of developing my portfolio. However, I'm facing a challenge with implementing next and previous buttons within my j ...

Why is the Jquery console not displaying any values?

Hey everyone, I need some help with a small issue in my project. For some reason, the console.log() function in my project is not returning any values. <script> $('#search-box<?=$x;?>').blur(function() { var val = $("#search ...

How can I save every attribute of an object, including functions, to a JSON file?

How can I save a Json file with both data and functions included? I have tried using JSONfn, but it doesn't preserve the functions for me. I attempted the following code, but it didn't achieve the desired outcome: fs.writeFile("object.json", ...

Tips for displaying additional JSON data within a single table cell in React

In my application, I have a table that displays the names of employees. Currently, there is an "EXPAND ALL" button that shows additional information for all employees at once. I am now working on implementing a feature that will expand and display the same ...

Should private members be kept confidential during program execution?

While Typescript's "private" members may not be truly private at runtime, traditional closures maintain the privacy of their members. Is there value in ensuring that private members remain private during runtime? ...

In my array, I have numerous objects that need to be inserted into a PostgreSQL database using a single query executed from a Node.js environment

After receiving the data from the frontend, all the information is stored in req.body. The next step involves mapping the data and attempting to insert it, however, an error is being encountered. router.post('/addItems', (req, res) => { ...

Error in Discord JS: Unable to access undefined properties (roles)

Currently, I am in the process of developing an event that will periodically check a MongoDB database for any expired keys and then proceed to remove a specific role from the corresponding member. const mongoose = require("mongoose") const { Disc ...

Struggling to make the grunt.js task for postcss with autoprefixer function properly

I am currently facing issues with using postcss in conjunction with autoprefixer-core. Even though the css is being generated correctly, autoprefixer doesn't seem to be applying any prefixes. I have already installed postcss and autoprefixer via NPM ...

Executing a search and replace function using a delay within a foreach loop - the ultimate guide

Below is a snippet of code where I attempt to perform find and replace within an array by searching for keys and replacing them with corresponding values. However, the expected functionality does not work as intended, leading to multiple searches for &apos ...

Saving the value of array[i] from a for loop into a fresh array results in undefined

I am currently developing a matching algorithm that compares two arrays of strings. If there is an exact match (===), it stores the results in the unSafeResult array. If there is a match using Regex, it stores the results in the warningResult array. Howeve ...