1

I created js function and now i want that js function to call itself only once, My code is

function view(str){ $.ajax({ type: "POST", url: '<?php echo base_url()?>index.php/main/'+str+'/', success: function(output_string){ //i want to call function from here only once like view(str); } }); } 

. How can i do that ? Thanks in advance, Currently it is showing me infinte loop.

1
  • i am calling that function on anchor tag click like<a onclick="view('myfucntion')" href="#"> Commented Mar 23, 2013 at 7:59

4 Answers 4

8

Use a flag variable

var myflag = false; function view(str) { $.ajax({ type : "POST", url : '<?php echo base_url()?>index.php/main/' + str + '/', success : function(output_string) { if (!myflag) { view(str); } myflag = true; } }); } 
Sign up to request clarification or add additional context in comments.

Comments

1

Try adding a parameter to the function that keeps track of the count:

function view(str, count) { if (count > 0) { return; } $.ajax({ type: "POST", url: '<?php echo base_url()?>index.php/main/'+str+'/', success: function(output_string) { view(count + 1); // i want to call function from here only once like view(str); } }); } 

Then you would initially call view like this:

view(str, 0); 

Comments

1

you are looking for jquery one. http://api.jquery.com/one/

fiddle http://jsfiddle.net/XKYeg/6/

<a href='#' id='lnk'>test</a> $('#lnk').one('click', function view(str) { $.ajax({ type: "POST", url: '<?php echo base_url()?>index.php/main/' + str + '/', success: function (output_string) { i want to call function from here only once like view(str); } }); }); 

Comments

1

You can pass a bool as a parameter on whether the function should call itself again:

function view(str, shouldCallSelf){ $.ajax({ type: "POST", url: '<?php echo base_url()?>index.php/main/'+str+'/', success: function(output_string){ if (shouldCallSelf) view(output_string, false) } }); } 

You should call it with true the first time. It will then call itself with false the second time, will not execute again.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.