Question

I am using JavaScript, jQuery and PHP. How do I limit the JavaScript function to execute once?

My MainJQuery file has Ajax. display.php 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 a 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 the 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 to limit to execute a JavaScript function in the jQuery Ajax success portion?

Was it helpful?

Solution

In jQuery you can use the .one() function to bind a method that will execute only once. For example,

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

See jQuery one help topic.

OTHER TIPS

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() {};
};

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.

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();

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

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top