0

I'm trying to imitate the ASP Master/Content page concept in PHP/jQuery environment, in which I can run an AJAX call in master page to include the content page dynamically. I added a div place holder in my master page and used the following code to add the content page dynamically:

     $.ajax({
         url: "ajax.php"
         , type: "POST"
         , data: {'cmd' : 'dashboardView'}
         , success: function(response, sts){
              if(response.flag)
              {
                   $("#divMainContentPHolder").html('');
                   $("#divMainContentPHolder").html(response.mainContent);
              }
              else
                   alert(" unsuccessful!");
         }
         , dataType: "json"
     });

The code is working fine, but the problem is, since there are some javascript functions in the content page, if the above function runs for the second time, the functions ill be duplicated, so that the run multiple times. I was wondering if someone could help me understand what is the best practice for such development. thank you

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
Fred
  • 378
  • 1
  • 10
  • 26
  • 1
    generally easiest to load all functions in main page, then call needed function for new content within success callback. Depends on scope and size of project. Can also use `getScript` and check if function already exists before loading it again. What sort of functions are you loading in content page? – charlietfl Mar 29 '13 at 16:57
  • most of the functions are for manipulating the data or running some other ajax calls for saving or retrieving data based on the user interaction. And of course a $(document).ready(function() {...}); in each content for using the plugins and other preparations. I'd like the idea of loading all functions in main page. I can even create different .js files for related javascript for each content and load them in the main page. But how can I deal with the $(document).ready portion of each content? – Fred Mar 29 '13 at 17:54

1 Answers1

0

If you want a function to run only once, simply name it in order to redefine it:

success: function onetimer(response, sts){
          if(response.flag)
          {
               $("#divMainContentPHolder").html('');
               $("#divMainContentPHolder").html(response.mainContent);
          }
          else
               {
               alert(" unsuccessful!");
               }

          onetimer = function(){}; /* redefine me as an empty function */
     }

Subsequent calls will do nothing.

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265