0

i have one piece of code which calls to an api service via JQuery ajax Post. Ajax calls a PHP file and PHP file calls a curl code which references to the API. Now I have called suppose 5 simultaneous calls and these calls takes around 15 seconds each.

Now suppose one call has returned response and I do not want to wait for the rest of them to finish. I want to execute a curl_close on all of them and move forward so that the next page doesn't waste time on closing all those curls. How can I achieve that.

Here are my three files:

Index.php

<?php

session_start();

?>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div><button onclick="startAjaxRequests();">Click To Start</button> </div>
<div id="output_div">
    Your output will be printed here:<br>

</div>
<div><button onclick="cancelXhrRequests();">Abort and Reload</button> </div>
<script>
    var xhrRequests = [];

    function startAjaxRequests() {
        var data;
        var cities = ["cairo", "pune", "dubai", "london", "jodhpur"];
        var lats = ["30.05", "18.52", "25.20", "51.50", "26.28"];
        var longs = ["31.23", "73.85", "55.27", "0.12", "73.02"];

        for(var i=0;i<cities.length;i++) {
            data = {latitude: lats[i], longitude: longs[i], section: "search_results"};
            var xhr = $.ajax({
                type: "POST",
                url: "location_penny.php",
                data: data,
                success: function (result) {
                    //cancel.html(result);
                    $("#output_div").append("Resutls for "+cities.toSource()+" are: "+result+"<br>");
                },
                async: true
            });
            xhrRequests.push(xhr);
        }
    }

    function cancelXhrRequests(){
        for (var i = 0; i < xhrRequests.length; i++) {
            xhrRequests[i].abort();
        }
        var data = {section: "close_curls"};
        $.ajax({
            type: "POST",
            url: "location_penny.php",
            data: data,
            success: function (result) {
                alert(result);
                window.location.href = 'http://127.0.0.1:8080/test/fork_curl/redirected.php';
            },
            async: true
        });
    }
</script>
</body>
</html>

Location_penny.php

<?php

error_reporting(E_ALL);
ini_set('max_execution_time', 300);
session_start();

$soapUrl = "my soap URL";

$api_username = "username";
$api_password = "password";

function apiAddittionalDetails($lat,$lang){
    global $soapUrl, $api_username, $api_password;

    $xml_addittional_details = 'The XML Request';

    $headers = array("Content-type: text/xml;charset=\"utf-8\"", "Accept: text/xml", "Cache-Control: no-cache", "SOAPAction: http://tempuri.org/IDynamicDataService/ServiceRequest", "Pragma: no-cache", "Content-length: " . strlen($xml_addittional_details));
    $url = $soapUrl;
    // PHP cURL  for https connection with auth
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000);
    curl_setopt($ch, CURLOPT_ENCODING , "gzip");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_addittional_details);
    // the SOAP request
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    // converting
    array_push($_SESSION['curls'], $ch);

    $response = curl_exec($ch);
    return $response;
    curl_close($ch);
}

if($_POST['section']=="search_results"){
    $response = apiAddittionalDetails($_POST['latitude'], $_POST['longitude']);
    $doc = simplexml_load_string($response);
    $add_nodes = $doc->xpath ('//Address');
    echo count($add_nodes);
}else if($_POST['section']=="close_curls"){
    $count = 0;
    foreach($_SESSION['curls'] as $curl_object){
        $count++;
        curl_close($curl_object);
    }
    echo $count;
}

?>

redirected.php

<?php

error_reporting(E_ALL);
ini_set('max_execution_time', 300);
session_start();

$soapUrl = "my soap URL";

$api_username = "username";
$api_password = "password";

function apiAddittionalDetails($lat,$lang){
    global $soapUrl, $api_username, $api_password;

    $xml_addittional_details = 'The XML Request';

    $headers = array("Content-type: text/xml;charset=\"utf-8\"", "Accept: text/xml", "Cache-Control: no-cache", "SOAPAction: http://tempuri.org/IDynamicDataService/ServiceRequest", "Pragma: no-cache", "Content-length: " . strlen($xml_addittional_details));
    $url = $soapUrl;
    // PHP cURL  for https connection with auth
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000);
    curl_setopt($ch, CURLOPT_ENCODING , "gzip");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_addittional_details);
    // the SOAP request
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    // converting
    array_push($_SESSION['curls'], $ch);

    $response = curl_exec($ch);
    return $response;
    curl_close($ch);
}

echo(date("Y-m-d H:i:s",time()));
echo "<br>";

$response = apiAddittionalDetails("30.05", "31.23");

echo(date("Y-m-d H:i:s",time()));
echo "<br>";

$doc = simplexml_load_string($response);
$add_nodes = $doc->xpath ('//Address');
echo count($add_nodes);

?>

If I click the abourt and redirect button on index.php while there are curl requests still being executed I don't see the page moving forward until 50-60 seconds which is the time I believe required in closing all the curl handles.

After that the page goes forward. I have tried the session technique but the code says curl object required while integer is passed in the location_penny.php file.

Anoop
  • 173
  • 1
  • 1
  • 14
  • I would do that using 5 different simultaneous ajax requests. When the first was success, I'd call a abort() function to cancel them all. http://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery – Leo Dec 13 '15 at 18:44
  • @Leo Tried this. It aborts the ajax requests. But somehow the curl handles are still open in the PHP server side and hence it takes lots of time to execute the href link. – Anoop Dec 13 '15 at 19:44
  • I got it. You can try this `CURLOPT_CONNECTTIMEOUT`. I'm not specialist, but I think you could consider, If your information don't change very fast (like stocks) to use a handmade cache.You could make ajax calls a xml or json files saved in your own server with the information you need, instead of calls a php which makes a curl request. Then you could schedule the PHP with the Curl request to execute and save all the xml/json once a day, for example. – Leo Dec 13 '15 at 22:23

0 Answers0