Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX Request - Add Additional GET request inner loop

I have a button at the top a table that displays a modal window to initiate a VOIP call - the ultimate aim is for it to call the first number in the list and then the 2nd number and so on. I've got it working in that it displays the modal window and allows me to initiate a call to the first number in the list.

I now need to update the script so that if the call is successful it then makes another AJAX request in a loop say every 5 seconds to check the status of the call. If the first call is successful it will return the following which I'm storing in the httpResponseText variable:

Authentication accepted<br/>ActionID = Jo9oACY52cp1

I need to parse out the ActionID value - in the above example this would be Jo9oACY52cp1 - and then have another GET request to get the status of the current call by passing in the ActionID as follows:

https://www.acme.com/GetStatus.php?ActionID=$action_id

This request returns 3 values - ActionID,UID,STATUS - like this:

xshsJ6Y2eLDC,1500806656.160,ANSWER

I'm only interested in the 3rd value - STATUS - and I need to keep checking the result of this request until the Status does not equal IN_PROGRESS. At this point I can then enable the Next Call button and start all over again.

Here's my current table and script:

$("#startBulkContactCall").click(function() {
  $(this).attr('selectedRow', '1');
  contactMobile = $($($('table > tbody > tr:nth-child(1) > td:nth-child(2)').children())[0]).attr('contactMobile');
  contactName = $($($('table > tbody > tr:nth-child(1) > td:nth-child(2)').children())[0]).attr('contactName');
  $('#callNextBulkContact').prop('disabled', true);
  firstURL = "<?php echo $callBackURL ;?>" + defaultCallBackNumber + "<?php echo $contactCallBack ;?>" + contactMobile;
  console.log('firstURL: ' + firstURL);
  $.ajax({
      url: "<?php echo $callBackURL ;?>" + defaultCallBackNumber + "<?php echo $contactCallBack ;?>" + contactMobile,
      data: {},
      type: "GET"
    })
    .then(function(data, status, xhr) {
      var httpStatus = status;
      var httpResponseCode = (xhr.status);
      var httpResponseText = (xhr.responseText);
      $('#ajaxSuccessBulk').html('Call in Progress').show();
      $("#startBulkContactCall").prop("disabled", true);
      $("#callNextBulkContact").prop("disabled", true);
    })
    .fail(function(xhr) {
      var httpStatus = (xhr.status);
      var httpResponseCode = (xhr.getAllResponseHeaders);
      var httpResponseText = (xhr.responseText);
      var ajaxError = 'There was an error requesting the call back. HTTP Status: ' + httpStatus + ' ' + httpResponseText;
      //make alert visible 
      $('#ajaxError').html(ajaxError).show();
    })
});

$('#callNextBulkContact').click(function() {
  $('#callBulkContact').attr('selectedRow', parseInt($('#callBulkContact').attr('selectedRow')) + 1);
  var rowNum = parseInt($('#callBulkContact').attr('selectedRow'));
  var row = 'table > tbody > tr:nth-child(' + rowNum + ') > td:nth-child(2)';
  contactMobile = $($($(row).children())[0]).attr('contactMobile');
  contactName = $($($(row).children())[0]).attr('contactName');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />


<button type="button" id="bulkCallButton" class="btn btn-default"><span class="glyphicon glyphicon-phone"></span> Bulk Call</button>


<table class="table table2 table-striped table-bordered" width="100%">
  <thead>
    <th scope="col">Name</th>
    <th scope="col">Mobile</th>
  </thead>
  <tbody>
    <tr id="D8F49748-212A-42D8-A188-4C23556027FA">
      <td><a href="details.php?action=contactLink&contactID=D8F49748-212A-42D8-A188-4C23556027FA">John Citizen</a></td>
      <td><a href="#" contactName="John Citizen" contactMobile="0412345678" data-toggle="modal" data-rec-id="1537" data-target="#contactCallModal"><span class="glyphicon glyphicon-earphone"></span> 0412 345 678</a></td>
    </tr>
    <tr id="EAD2DCCA-7EFA-B048-AD7D-8FCC0ED5EFD7">
      <td><a href="details.php?action=contactLink&contactID=EAD2DCCA-7EFA-B048-AD7D-8FCC0ED5EFD7">Jonah McMahon</a></td>
      <td><a href="#" contactName="Jonah McMahon" contactMobile="0490876543" data-toggle="modal" data-rec-id="1538" data-target="#contactCallModal"><span class="glyphicon glyphicon-earphone"></span> 0490 876 543</a></td>
    </tr>
    <tr id="D9AA7744-E138-4A0E-86A2-B8D0CD2007D6">
      <td><a href="details.php?action=contactLink&contactID=D9AA7744-E138-4A0E-86A2-B8D0CD2007D6">Jake Simpson</a></td>
      <td><a href="#" contactName="Jake Simpson" contactMobile="0405999666" data-toggle="modal" data-rec-id="1577" data-target="#contactCallModal"><span class="glyphicon glyphicon-earphone"></span> 0405 999 666</a></td>
    </tr>
  </tbody>
</table>


<div class="modal" id="contactBulkCallModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title">Call Contact</h4>
      </div>
      <div class="modal-body">
        <p>Calling </p>
      </div>
      <div id="ajaxError" class="alert alert-danger text-center" role="alert" style="display:none">
        Error Response
      </div>
      <div id="ajaxSuccess" class="alert alert-success text-center" role="alert" style="display:none">
        Call in Progress
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" id="startBulkContactCall" class="btn btn-success">Start Call</button>
        <button type="button" id="callNextBulkContact" class="btn btn-success">Next</button>
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

Never had to do such a complex AJAX request (at least for me) and not sure where to start to add the additional request in loop?

like image 200
user982124 Avatar asked Oct 18 '22 08:10

user982124


1 Answers

Here's what I would do: first separate code in functions, it will makes things way easier to follow.

startCall should initiate your call, it receives the callURL the ajax should use. It returns a promise that will resolve once it is made.

monitorCall takes a callID, and a Callback (third param "failed_tries" is used internally.) It will fire the status check using ajax, and call itself every 5 seconds until either 5 consecutive fails happen, or until we get the correct status. The callback is a usual JS callback with error and result as arguments.

getMonitoredCall will join the former two functions together to give a promise that will resolve once the call ends.

getNewCallUrl is used to provide another call. This function will be called before each call, to retrieve who to call. There is work left for you there! It should return a promise that gives the URL as result.

Finally, loopCalls initiates everything and once a call is complete, will call itself again to follow-up on the next call until something fails.

function startCall(callURL){
    return $.ajax({
        url: callURL,
        data: {},
        type: "GET"
    }).then(function(data, status, xhr) {
        var httpStatus = status;
        var httpResponseCode = (xhr.status);
        var httpResponseText = (xhr.responseText);
        $('#ajaxSuccessBulk').html('Call in Progress').show();
        $("#startBulkContactCall").prop("disabled", true);
        $("#callNextBulkContact").prop("disabled", true);

        return Promise.resolve(xhr.responseText.match(/ActionID = (.+)/)[1]);
    })
    .fail(function(xhr) {
        var httpStatus = (xhr.status);
        var httpResponseCode = (xhr.getAllResponseHeaders);
        var httpResponseText = (xhr.responseText);
        var ajaxError = 'There was an error requesting the call back. HTTP Status: ' + httpStatus + ' ' + httpResponseText;
        //make alert visible 
        $('#ajaxError').html(ajaxError).show();
    });
}
function monitorCall(callID,callback,failed_tries){
    failed_tries = failed_tries || 0;
    $.ajax({
        url: 'https://www.acme.com/GetStatus.php',
        data: {ActionID:callID},
        type: "GET"
    }).then(function(data){
        if(data && data.split(',')[2] != "IN_PROGRESS"){
            callback(null,data);
        }else{
            setTimeout(monitorCall.bind(null,callID,callback,0),5000);
        }
    }).fail(function(xhr){
        failed_tries++;
        if(failed_tries>5){
            callback("Error trying to get the status, stopping after 5 consecutive tries.");
        }else{
            setTimeout(monitorCall.bind(null,callID,callback,failed_tries),5000);
        }
    });
}

function getMonitoredCall(callUrl){
    return new Promise(function(resolve,reject){
        startCall(callUrl).then(function(callID){
            monitorCall(callID,function(err,res){
                if(err){
                    reject(err);
                }else{
                    resolve(res);
                }
            });
        });
    });
}

function getNewCallUrl(){
    return $.ajax({
        url: "http://getNewCallUrl/",
        data: {},
        type: "GET"
    }).then(function(data, status, xhr) {
        //Let's presume the request simply returns a call URL.
        return Promise.resolve(data);
    })
    .fail(function(xhr) {
        var httpStatus = (xhr.status);
        var httpResponseCode = (xhr.getAllResponseHeaders);
        var httpResponseText = (xhr.responseText);
        var ajaxError = 'There was an error requesting the call back. HTTP Status: ' + httpStatus + ' ' + httpResponseText;
        //make alert visible 
        $('#ajaxError').html(ajaxError).show();
    });
}

function loopCalls(){
    getNewCallUrl().then(function(callUrl){
        return getMonitoredCall(callUrl);
    }).then(function(){setTimeout(loopCalls,5000)});
}
loopCalls();
like image 81
Salketer Avatar answered Oct 21 '22 07:10

Salketer