0

I'm trying to reinvoke the code inside the document's ready() function inside an ajax callback. Is this possible?

$(document).ready(function() {
  // page initialization functions
  alert('hi');
});

// this gets called from a button click on the screen
function reauth() {
  // logic here omitted for brevity
  $.post("/Base/reauth", $("#reauthForm").serialize(), function(data) {
    if (data.result != null) {
      $(document).ready();  // <-- this does not invoke the alert('hi');
    }
  });
}
Adam Levitt
  • 10,316
  • 26
  • 84
  • 145

2 Answers2

4
function sayHi() {
  alert('hi');
}

$(document).ready(function() {
  // page initialization functions
  sayHi();
});


// this gets called from a button click on the screen
function reauth() {
  // logic here omitted for brevity
  $.post("/Base/reauth", $("#reauthForm").serialize(), function(data) {
    if (data.result != null) {
      sayHi();
    }
  });
}
Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
  • +1 a much more elegant way of doing it, as opposed to 'faking' a second/third/n+1 document ready event. – Rory McCrossan May 26 '12 at 19:39
  • Is there any way to do it without a special function? – Adam Levitt May 26 '12 at 19:55
  • The special function is the point! In reality it will not be `sayHi()` but `doDocumentReady()`. Code, that is supposed to run on `ready()` **and** at an other point in time should not be in `ready()`, but somwhere external. – Eugen Rieck May 26 '12 at 19:58
  • The thing is I want to have the reauth method exist in a common.js file that exists on EVERY page and thus generically re-calls the current page's $(document).ready() in a seamless way. – Adam Levitt May 26 '12 at 20:21
  • So you have the `sayHi()` resp. `doDocumentReady()` method in the same file and you are there! – Eugen Rieck May 26 '12 at 22:38
2

Can't you just put a function inside ready block:

function something() {
   alert('hi');
}

$(document).ready(function() {
   something();
});

And then call it again?

WojtekT
  • 4,735
  • 25
  • 37
  • The second `function(){...}` is not needed. `$(document).ready(something);` is sufficient. If bits are costy, one can also use `$(something);`, which is equivalent. – Rob W May 26 '12 at 19:38
  • This solution is more generic if, for example, you would later need to add some arguments to `something` function. – WojtekT May 26 '12 at 19:40