'How to refresh a div without reloading the entire page?

I have a div and I want to refresh its content without reloading the entire page.

I tried many times with many methods (ajax call, javascript, etc...), but I don't have did it.

My div displays the entire content of ModelName.all And in this particular div, we can add new entities (thanks to a form) of the Model I use.

I display this div thanks to a Rails Partial View.

Currently, I use this when the user submit the form :

$('#ArticlesDiv').html("<%= escape_javascript (render partial: 'articles') %>");

But it seems my partial view doesn't have an up-to-date model. Because before I add the new entity, I see for example 5 elements, and after I add the new entity, I see again 5 elements. For test purposes, I use a javascript alert which displays ModelName.all.count

And the alert displays 5 ! But when I look at my database content (before the alert), I can see 6 elements ! And when I refresh my page manually, the div displays 6 elements.

Code to explain :

The main view :

<div id="ArticlesDiv">
  <%= render(:partial => "articles") %>
</div>

_articles (the partial view) :

<script>
  alert('<%=Article.all.count%>');
</script>

<% Article.all.each do |article|) %>

<strong><%= article.name %></strong><br />

<% end %>

My goal is to have a smooth interface which it doesn't reload the entire page any times you add an other article.



Solution 1:[1]

You can have the contents of the div in a partial and load just the content using a URL say, /divcontents. You can refresh the <div> using .load():

$('#ArticlesDiv').load("/divcontents");

Solution 2:[2]

Try to use load function jQuery, you should do something like this:

HTML:

<div id="div1"></div>
<button type="button" id="button">Test</button>

jQuery:

$(document).ready(function(){
    $("#button").click(function(){
        $("#div1").load("demo_test.txt");
    });
});

Solution 3:[3]

<script>
$(document).ready(function () {
    // will call refreshPartial every 5 seconds
    setInterval(refreshPartial, 5000)

});

// calls action refreshing the partial
function refreshPartial() {
  $.ajax({
    url: "page_url",
    dataType: 'script',
    format: 'js'
 })
}
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Praveen Kumar Purushothaman
Solution 2 praguan
Solution 3 Atchyut Nagabhairava