views:

113

answers:

2

I have written a simple jQuery.ajax function which loads a user control from the server on click of a button. The first time I click the button, it goes to the server and gets me the user control. But each subsequent click of the same button does not goes to the server to fetch me the user control.

Since my user control fetches data from db, I need to reload the user control everytime i hit the button. But if anyhow I get my user control to unload from the page, and re-click the button, it goes to the server and fetches me the user control. Here's the code:


$("#btnLoad").click(function() {
    if ($(this).attr("value") == "Load Control") {
 $.ajax({
  url: "AJAXHandler.ashx",
  data: { "lt": "loadcontrol" },
  dataType: "html",
  success: function(data) {
   content.html(data);
  }
 });
 $(this).attr("value", "Unload Control");
    }
    else {
 $.ajax({
  url: "AJAXHandler.ashx",
  data: { "lt": "unloadcontrol" },
  dataType: "html",
  success: function(data) {
   content.html(data);
  }
 });
 $(this).attr("value", "Load Control");
    }
});

Please let me know if there is any other way I can get my user control loaded from server everytime I click the button.

+1  A: 

If your btnLoad is inside the user control you're reloading, you need to do this instead:

$("#btnLoad").live('click', function() {

When loading ajax, you're replacing the elements, and any event handlers bound directly to them. If you use .live() instead, it won't be destroyed as part of the callback...it works differently and the event handler lives higher in the DOM, so it doesn't get blown aware with the button itself.

Nick Craver
btnLoad is not part of my user control. When I click btnLoad, it loads the user control. I tried to use live though with no luck.
Ashish
+2  A: 

Add a cache property with the value false to the objects you pass to jQuery.ajax.

 $.ajax({
  url: "AJAXHandler.ashx",
  cache: false,
  data: { "lt": "loadcontrol" },
  dataType: "html",
  success: function(data) {
   content.html(data);
  }
 });

You can set this globally by:

jQuery.ajaxSetup({
    cache: false
});

jQuery will used cached responses for anything except SCRIPT/ JSONP by default.

Matt
Thanks Matt. Issue resolved.
Ashish