Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing to execute a JavaScript function more than once

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?

like image 980
venkatachalam Avatar asked Nov 29 '22 07:11

venkatachalam


1 Answers

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.

like image 107
redsquare Avatar answered Dec 06 '22 09:12

redsquare