views:

3228

answers:

6

Dear All I am using Javascript JQuery and PHP. My doubt isHow to limit the javascript function to execute once?

My MainJQuery file has ajax, display.php ,it execute for a while

    ....

          $.ajax({
      type:'POST',
      url: 'display.php',
      data:'id='+id  ,
      success: function(data){
                     $("#response").html(data);

                             //Here Get_list should be execute only once   
                              get_list('get');

                            // display should execute as usual  
                             display();

      }//success
          }); //ajax   
                .......

get.Php file writes value to Javascript

<?php
  print "<script language='javascript'>";
  print " g_cost[g_cost.length]=new Array('STA-VES','East',4500);"; 
  print " g_cost[g_cost.length]=new Array('STA-CRF','West',5400);"; 
  print "</script>";  

  ?>

My Javascript function has following value from php

function get_list('get'){

    for(var i=0;i<g_cost.length;i++)
      var temp = g_cost[i];

 var Name = temp[0];
        var direction = temp[1];
 var cost = temp[2];

        ..
        some code
        ... 
  }

  function display(){

    for(var i=0;i<g_cost.length;i++)
      alert(g_cost.length);
      var temp = g_cost[i];
      alert(temp[0]);
      alert(temp[1]);
      alert(temp[2]); 

  }

Is it possible limit to Execute a javascript function ,In JQuery ajax Success Portion; Any way to do this?

A: 

umm, try disabling the ajax trigger (link, button, etc.) after a successful call.

example of a trigger :

<a id="ajax_trigger" href="#" onclick="yourAjaxCall(); return false;">Get List</a>

...

            success: function(data){
                    $("#response").html(data);

                         //Here Get_list should be execute only once   
                          get_list('get');

                        // some code to disable, or hide #ajax_trigger
                        // in other words, make it unclickable or disappear.
                        $("#ajax_trigger").css('display': 'none'); // iirc

                        // display should execute as usual  
                         display();

            }//success
andyk
+3  A: 

Three options:

  1. Set a boolean flag in global scope, set it after a successful run, and check it before running

  2. After a successful run, disable the button (or whatever control you are using to call the one-time method)

  3. Slightly less preferred, but you can also do the validation on server side, i.e. call the method each time, but validate on server-side. The up side is that this will ensure data consistency on the server.

Yuval A
Introducing global variable is a bad idea.
Rene Saarsoo
+1  A: 

To create a function that executes only once:

get_list = (function(){
  var counter = 0;
  return function(param1, param2, ...) {
    if (counter > 0) {
      return;
    }
    counter++;

    // your normal function code here
  };
})();

This is almost the same as using a global variable for tracking how many times function is executed, except that instead of a global variable we create a variable, that only the inner function can see. After that you use it get_list as any other function.

This could probably be refactored into something more general in function prototye, so it could be used like this:

get_list = (function (param1, param2, ...) {
  ...
}).once();
Rene Saarsoo
+7  A: 

in jQuery you can use .one() function to bind a method that will execute only once

e.g

$("#someAnchorId").one("click", function(){
    //Ajax method here 
});

see jquery one help topic

redsquare
+1  A: 

Fastest way is to add one extra line to success declaration:

$.ajax({
    type:'POST',
    url: 'display.php',
    data:'id='+id  ,
    success: function(data){
        if(!arguments.callee.stop){ arguments.callee.stop = true; }else{ return; }

        $("#response").html(data);
        //Here Get_list should be execute only once   
        get_list('get');

        // display should execute as usual  
        display();

    }//success
}); //ajax
Using arguments.callee is really smart, thanks for this!
Chu Yeow
+1  A: 

You can replace the function with an empty function - this is essentially the same as Rene Saarsoo' solution, but looks nicer:

var get_list = function(param1, param2, ...) {
     // your code here
     get_list = function() {};
};
weirdan
in section "// your code here" you leave code that will run once, in subfunction you put code to run every time.
jmav