I'm using JQuery to get the value of the tags data-code
and its id
and add them to a javascript object to pass them via ajax to a PHP script. The PHP script grabs some data from an other server, processes the data and return the result to the ajax call. The code works correctly but I noticed that sometimes the result is simply not returned, nor any error is returned too. This seems to happen when the internet connection is not a hight speed connection such as that of my company, but I'm not sure about my 'diagnosis'.
The following is the working code:
var codeArray = [];
var obj = {};
// select all .rating[data-code] class tags and get the 'data' value.
// add the values to a javascript object the pair key:value i.e. {"16": "74875932", "17": "98548957"}
$('.rating[data-code]').each(function() {
var code = $(this).data('code');
var id = $(this).attr('id');
obj[id] = code
});
codeArray.push(obj);
// If codeArray is not empty send IDs and CODEs to PHP and get results back
if(codeArray.length > 0) {
$.ajax ({
type: "post",
url: "ajax.curl.php",
data: {codeArray},
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
},
success: function(data) {
$.each(data, function(key, value){
$('#' + key).children().html(value);
});
}
});
}
This is the PHP code. I'm using CURL to get the HTML content
$codeArray = $_REQUEST["codeArray"];
foreach($codeArray as $number => $number_array) {
foreach($number_array as $key => $value) {
// process the data
}
}
// output in json format
echo json_encode($output);
function get_url_contents($url) {
$crl = curl_init();
curl_setopt($crl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
curl_setopt($crl, CURLOPT_URL, $url);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLOPT_CONNECTTIMEOUT, 5);
$ret = curl_exec($crl);
curl_close($crl);
return $ret;
}
Any suggestion? Is the server where I'm getting the data from that's blocking something? Consider that the number of 'codes' that javascript passes to the PHP script is no more than 5 or 6. I'm not working with hundreds or thousands of calls.
I tried to add sleep(1)
in each PHP loop to slow down the requests but it did not change anything.