Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.getJSON works only once for each control. Doesn't reach the server again

First my code

$.getJSON("./posts/vote/" + postId + "/1", null, function(result) {
   if (result.result == true)
      $("#pst" + postId + " > .pstside > .rank > .score").html(result.voteCount);
 });

I have a bunch of buttons each with code which brings some voting results from an ASP.Net MVC controller action.

This works well the first time the button is clicked, but if it is clicked again nothing happens. Nothing reaches the server.

I am testing on FireFox.

What is going wrong? Some kind of weird caching? Because the request never reaches my controller the second time, the javascript seems to execute okay but keeps returning the old values.

like image 944
Cyril Gupta Avatar asked Aug 28 '09 06:08

Cyril Gupta


1 Answers

Sounds like a browser cache issue (if is that I'm pretty sure that is happening with IE), you may want to use $.ajax and set the cache option to false, since it is false by default only for dataType script and jsonp:

$.ajax({
  type: "GET",
  url: "./posts/vote/" + postId + "/1",
  success: function (result) {
    if (result.result == true)
      $("#pst" + postId + " > .pstside > .rank > .score").html(result.voteCount);
  },
  dataType: "json",
  cache: false
});

Or you could set that option globally, for all the jQuery Ajax functions, using $.ajaxSetup before using $.getJSON:

$.ajaxSetup({ cache: false });

Edit: You can do a POST request returning JSON like this:

$.post("./posts/vote/" + postId + "/1", 
  function (result) {
    if (result.result == true)
      $("#pst" + postId + " > .pstside > .rank > .score").html(result.voteCount);
  }, "json");

If you plan to do a lot of postJSON request, you can make your own function:

jQuery.postJSON = function(url, data, callback) {
    jQuery.post(url, data, callback, "json") ;
};

And you'll be able to use it just like $.getJSON

like image 90
Christian C. Salvadó Avatar answered Oct 20 '22 01:10

Christian C. Salvadó