2

I have an ajax function, and I expect it to run 1912 times, but it only runs once, for some reason. I'm using startAt, and stopAt to determine when it should stop running, but it's not working for some reason. What am I doing wrong?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript"> 
function callAjax(gotoUrl, link, startAt, stopAt, output) {

  $.ajax({
    type: "POST",
    url: gotoUrl,
    data: { link : link },
    error: function(xhr,status,error){
      alert("error");
    },
    success:function(data) {
      document.getElementById(output).innerHTML += startAt;
    },
    complete:function(data) {
      startAt++;
      var link = data; 
      if (startAt < stopAt) {
        setTimeout(function(){ 
            callAjax(gotoUrl, link, startAt, stopAt, output) 
        }, 100);
      }
    }
  });

} //end of function callAjax()  
</script>

<body onload = 'callAjax("test1.php", "link", 1, 1912, "output")'>
<div id = "output"></div>

Result:

1

Expected Result:

1912
5
  • you are putting the startAt++; inside an async call, why not put it befora actually performing the ajax call? Commented Oct 27, 2015 at 1:47
  • Why do you need the setTimeout() call? Just call the function... Commented Oct 27, 2015 at 1:50
  • 1
    @Chris I want pause for 100 miliseconds. Commented Oct 27, 2015 at 1:51
  • @Sudakatux It works when I put it inside success. What that suppose to happen? Commented Oct 27, 2015 at 1:54
  • 1
    Try console.logging data inside the complete event to ensure this is even firing... Commented Oct 27, 2015 at 1:55

1 Answer 1

2

The issue is on this line:

var link = data; 

you are reassigning the value of link to be the returned data.

You then immediately call this inside the timeout:

callAjax(gotoUrl, link, startAt, stopAt, output)

But link isn't a link any more its an object, hence jquery errors out, and silently dies after one iteration.

Removing that line makes the code function fine, you just need to store the data in another variable and it'll work.

Here's a fiddle with the functional code with just that line commented out.

Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way to convert the object back to string?
It really depends on what that object is.
There are different types of object? What are the main types?
Wait. You mean like arrays, and such?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.