Jump to content

How to make AJAX requests while a PHP script is running


CrimpJiggler

Recommended Posts

I made a PHP spider which downloads a series of wiki pages from a list, I put a 2 second delay in there so as not to cause excessive traffic and as a result, it takes a long time to load. I want to make the script tell you its made every time it saves a file, i.e. File 1 has been saved, file 2 has been saved etc. How can I make the PHP script make an AJAX request each time it iterates through a loop?

Link to comment
Share on other sites

You could save a message to a file and just have JS call a PHP page loading the contents of that file. Another option is to just run the script in a terminal, where echoing out a string will show right in front of you live.

I tried your first solution, heres the PHP script:

echo '<div id="status_update">
STATUS UPDATE SHOULD APPEAR HERE
</div>';

for ($i=1; $i < 10; $i++) {

	echo "Number $i<br>";
	
	$fh = fopen('include/status_update.txt','w');
	fwrite($fh,"Line $i");
	fclose($fh);
	
	sleep('3');
	
}

and heres the javascript:

function status_update() {

	var xmlhttp;
	if (window.XMLHttpRequest)
	  {// code for IE7+, Firefox, Chrome, Opera, Safari
	  xmlhttp=new XMLHttpRequest();
	  }
	else
	  {// code for IE6, IE5
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	  }
	xmlhttp.onreadystatechange=function()
	  {
	  if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
		document.getElementById("status_update").innerHTML=xmlhttp.responseText;
		}
	  }
	xmlhttp.open("GET","include/status_update.txt",true);
	xmlhttp.send();
	
}

setInterval(function(){ status_update(); },1000);

but it doesn't work, the AJAX doesn't seem to load while the PHP script is loading. In the PHP script, I put in sleep('3') which makes the script wait 3 seconds for each iteration of the loop, that would be plenty of time for the javascript to make these AJAX requests.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.