1

is it possible to display foreach loop response during iteration using jQuery or Ajax ?

for($i = 0; $i < 1000; $i ++) {
    echo $i;
    echo '<br>';
}

I want to call the function using ajax and display $i value in each iteration. Is it possible ?

Like typically, I dont want to wait for full page forloop process end and then echo result.

PS: I am student of Software Engineering in 2nd semester. I am in learning process so please bear me for any foolish request.

Thanks and Regards.

Hannah James
  • 540
  • 3
  • 14
  • As far as I know you can not do that with Ajax/PHP. If I understand your question correctly you whant a sort of real time connection. For that you will need to use websockets. PHP support websockets but in my opinion sockets work nicer with node.js – Baracuda078 Oct 19 '21 at 20:30
  • But in your example a loop of 1000 will be verry fast. If you run other code in the loop then just returning the index you could also write some code to store the response in a cache file or store it into the ram with apcu or redis the response will then be verry fast. – Baracuda078 Oct 19 '21 at 20:36
  • @Baracuda078 thanks for answer. Actually i add a simple example so user can understand my question. Is'nt it possible to call function using ajax and inside function we add foreach loop and print the value of $i using ajax response ? – Hannah James Oct 19 '21 at 20:40
  • In PHP you could add the result to an array. before your loop you can create a empty array like `$dataToReturn = []` in your for loop you add the data to the array like `$dataToReturn[] = $i` after the loop turn the array into a json string, then in your ajax complete function you can loop through the response and add it to the DOM – Baracuda078 Oct 19 '21 at 20:48
  • The first part of my comment I was wrong. It is possible like they explain in this [question](https://stackoverflow.com/questions/5415665/show-results-while-script-is-still-executing/5415754) but i really think returning the result in 1 json string will be better for your server for performance. I just tested some examples in this link and i got a fatal error because of `Maximum execution time of 30 seconds exceeded` you could increase the max execution time but only do that when it is really needed and you cant implement an other solution – Baracuda078 Oct 19 '21 at 21:08

0 Answers0