Amit Pal
Amit Pal

Reputation: 11052

Getting 304 Error in response of jquery request

Scenario:

  1. User visit the page

  2. Jquery started to make ajax request to backend code

  3. Navigate to page (not refreshing) I can see the request still going to server from client. It supposed to be stopped now.

  4. When user return to same page again, Request should started to hit but it's throwing 304 error. Jquery supposed to hit the request again.

User click on following button code

index.html.erb

<td colspan="3"><%= link_to 'Show state', simulation, :class => 'btn btn-primary' %></td>

will navigate to

show.html.erb

Here I have written the jquery code to making Ajax request

<script>
$(function() {setInterval(function(){ $.get("/posts/<%= @post.id %>"); }, 5000);
});
Dom needed to be changes after every `Ajax` response in same views (show.html.erb)

<span id="post-data">
  <table class = 'table table-hover'>
     .....
  </table>
</span>

js file for rendering the views

in show.js.erb

$("#post-data").html(" <table> ... </table>") 

How can I fix these errors. Any help would be appreciable, I am not a core javascript guy.

What I am looking for?

Upvotes: 3

Views: 2315

Answers (1)

Manohar Gunturu
Manohar Gunturu

Reputation: 696

When it rans for the second time, it will return the cached content from the browser, as it should per the specification:

For 304 Not Modified responses that are a result of a user agent generated conditional request the user agent must act as if the server gave a 200 OK response with the appropriate content.

jQuery istn't generating any responses here. And the 304-header is just an HTTP header. HTTP AJAX requests are ordinary HTTP requests and may return any valid header. If the server responds with 304, the XHR object will simply serve up the locally cached response from the server. It's completely transparent for the user, though.

You could use the cache parameter in the ajax request then it may work:

   $.ajax({
         url: ".....",
         dataType: "json",
         type: "GET",
         cache: false,
         contentType: "application/json",
         success: function (data, textStatus) {
            console.log("RECV: " + data);
         }
      });

Upvotes: 2

Related Questions