How to make Multiple AJAX calls

I have created two simple DEMO web pages that both use AJAX to call PHP scripts.

  1. first PHP script has No delay

  2. second calls PHP script with a 2 second delay

The PHP script that AJAX calls:

<?php
  declare(strict_types=1);
  error_reporting(-1);
  ini_set('display-errors', 'treu');


  $urls = explode("\n", $_POST['myTextArea']);
  
  foreach( $urls as $id => $url):
    $url = trim($url);
    if( empty( $url ) ):
      // echo '<br>PREVENT BLANK LINES';
    else:  
      echo '<div class="bgs bd1 bdr p42">';
        echo '<h1>' .$url .'</h1>';
      echo '</div>';  
      echo '<h4 class="dib tac"><b> ¯\_(ツ)_/¯  </b></h4>';

    /*
      sleep( 2 ); // seconds
    */

    endif;  
  endforeach;

The 2 second delay is to emulate the PHP processing time.

I would like AJAX to process multiple requests and NOT to overwrite the previous request as can be seen in this multiple request demo

I have been trying for the past couple of days to search for a solution without success and would be very grateful for a solution.

Sorry, but I’m not grasping what I’m looking for on what page. Do you mean the “no delay” and “2 second delay” pages should be showing all 4 versions, the https://www, https://, http://www, and http:// responses?

Requests as such can’t be overwritten… do you mean you don’t want to replace the rendered response? In that case, don’t replace the .innerHTML of the result element but add to it:

document.getElementById('status').innerHTML += xhr.responseText

Or better yet, .insertAdjacentHTML() to avoid reparsing (and potentially corrupting) the existing contents:

document.getElementById('status').insertAdjacentHTML(
  'beforeend',
  xhr.responseText
)
2 Likes

I would like the user to be able to enter numerous URLs and to be able to compare the results.

At the moment curl is used to find the results of http, http://www, Https and Https://www. Each has a curl timeout of about ten seconds. Ajax waits until every Ajax request has completed and before displaying all the URL curl results… meanwhile the page looks as though it has stop responding.

I would like each URL batch result to be displayed then continue with the next batch of http requests.

I was able to display each batch but it was overwritten by the next batch.

I hope this explanation is more clearer.

Many thanks, I will give it a try when I am back on the desktop.

Eh? Why emulate anything? Why not simply string the AJAX calls into one another so that you get the results as soon as possible?

I have been trying without success for the past couple of days.

Currently the results do not come “as soon as possible” the page freezes until all the results are available and then they all come at once :slight_smile:

Try this page, select “samples”, then “simple” and note the time taken for the results to appear:

https://supiet2.tk/

Ideally I would like a hidden table to appear once the “simple” button has been selected and rows appearing as soon as the results are available.

So the timing issue is a question of reversing the paradigm;
Rather than sending PHP a block of URLs and saying “go do this.”, split the URLs at the Javascript end and fire multiple AJAX requests at the PHP script handing it a single URL at a time. That way the script can catch each return as soon as it’s done.

1 Like

I managed to split the URLs at the JavaScript level,. eventually because I could not get split to work with \n. Searched and found a solution,

Next problem was getting the ajax call to work. Weird problem encountered - if an alert was activated all the URL results would display OK but when removed overwrites would occur and only the last URL would show?

My JavaScript knowledge is very limited but trial and error managed to solve all the problems.

Default screen now shows 20 URLs and clicking on the Test URLS button gracefully renders eighty different results.

The latest version, complete with warts and remmed debug script can be seen here:

https://this-is-a-test-to-see-if-it-works.tk/ajax/index.php

Beware:

Copying and pasting the source code will only show results if a separate _ajax-posts.php exists.

var lines = txtBox.value.replace(/\r\n/g,"\n").split("\n");

This can be somewhat reduced as
var lines = txtBox.value.split(/\r?\n/);

Not sure why that would be the case. Personally i’d still avoid manipulating the same innerHTML element over and over (just because i’m leery of parallel processes returning at the same moment), and instead insert a new <div> or table row using the insertAdjacentHTML as m3g4p0p suggested.

I’m guessing that’s why the alert() seemed to work OK. Because message boxes stop code until they are interacted with they kind of forced the parallel into sequential.

1 Like

Many thanks, I have implemented the changes in the latest version also tidied the scrips and got rid of a load of unused remmed statements.

I have also added some notes for my benefit when I modify the scrips at a later date…

The Ajax scripts were a mess while trying to get everything to work. Once the junk was removed the rendering time is virtually instant I am delighted to say :slight_smile:

Revised script:

<?php 
  declare(strict_types=1);

?>
 
//=====================================================    
// called from: <input onclick="ajax_post( mode );">
function ajax_post( mode )
{
  // get textarea string and split on new lines
  var txtBox = document.getElementById("myTextArea");
  var lines = txtBox.value.split(/\r?\n/);

  // iterate all URLs and call AJAX
    for (var i2 =  0; i2 < lines.length; i2++)
    {
      if( lines[i2].length > 2)
      {
        ajax_call( mode, lines[i2], i2 );
      }  
    }
}


//=====================================================    
// called from: result = ajax_call( mode, lines[i2], i2 );
function ajax_call( mode, url2, i2 )
{
  // alert( tx );
  // Create our XMLHttpRequest object
  var hr = new XMLHttpRequest(i2);

  // Create some variables we need to send to our PHP file
  var url  = "_ajax-posts.php";
  var vars = "url2=" + url2 + '&mode=' +mode +'&i2=' +i2;  

  hr.open("POST", url, true);

  // Set content type header information 
  // for sending url encoded variables in the request
  hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  // Access the onreadystatechange event for the XMLHttpRequest object
  hr.onreadystatechange = function()
  {
    if(hr.readyState == 4 && hr.status == 200)
    {
      var return_data = hr.responseText;
      document.getElementById('ajaxOutput').innerHTML += return_data;
    }
  }
  // Send the data to PHP now... 
  // ...and wait for response to update the status div
  hr.send(vars); // Actually execute the request
  // DOES NOT HIDE "processing URLs..." WHEN FINISHED ???
  document.getElementById('ajaxOutput').innerHTML = ''; // "processing URLs...";
}

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.