Your problem is that you're trying to send a JSON response to the client but include in that JSON response the time it took to generate the response. That's kind of impossible, but you then approximate it by including the time it took to generate the response but excluding the time it took to generate the time it took to generate the response (more realistic).
I think the simplest solution would be:
$start2 = microtime(true);
$all = json_encode(array(iterator_to_array($cursor),$timeExecuted));
$end2 = microtime(true);
$result = ($end2-$start2);
echo json_encode(["all" => $all, "result" => $result ]);
However in the client side you now need to do:
success: function (data) {
var all = JSON.parse(data.all);
var time = data.result;
}
You could also do some sort of botch fix which may or may not work like:
...
echo "[" . json_encode($result). ", ". $all . "]";
Then you can access result like:
success: function (data) {
var time = data[0];
var all = data[1];
}
Beware when you use the 2nd way. It's generally bad practice because of odd encoding issues that may come up. Here it should be ok because $result
is a number, but in general, it's not the best solution.
Note: Don't forget to set content headers before echoing anything, this will tell AJAX that it received a JSON response and will parse it accordingly:
header("Content-Type: text/json");
3rd solution which may or may not work (not tested):
$start2 = microtime(true);
$all = json_encode(array(iterator_to_array($cursor),$timeExecuted));
$end2 = microtime(true);
$result = ($end2-$start2);
header("Content-Type: text/json");
header("X-Encoding-Time: ".$result);
echo $all;
And in your AJAX:
success: function (data, textStatus, request) {
var all = data;
var result = request.getResponseHeader("X-Encoding-Time");
}