how to show results one by one in codeigniter 4 for loop with ob_flush - xmlhttprequest

my problem is: i wan to show data in real time with codeigniter 4
This code results will be out once the for loop is ended
what i wan to do is echo results one by one
i have alrady done this before but not with codeigniter, it's was my own code without any framwork
but now i am stiked here 1 week and no rsults
i use codeigniter 4
and i use aapanel in my server
and this is my phpinfo
my function in my controller Count.php
function startcounter(){
$count = $this-\>request-\>getPost("count");
if (ob_get_level() == 0) ob_start();
for($i=0; $i\<=$count; $i++){
echo $i;
ob_flush();
flush();
sleep(1);
}
ob_end_flush();
exit();
}
My javascript
function startcounter(){
data = "count=5";
var xhr = new XMLHttpRequest();
xhr.open('POST', baseUrl+'/count/startcounter', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState == 1) {
resp = xhr.response;
arrs = resp;
if (xhr.readyState == XMLHttpRequest.LOADING) {
console.log(xhr.responseText);
}
if (xhr.readyState == XMLHttpRequest.DONE) {
alert('Done')
}
}
}
}

function testflush(){
ini_set('output_buffering','on');
ini_set('zlib.output_compression', 0);
ini_set('max_execution_time', '3000');
ob_implicit_flush();
$response = service('response');
$response->send();
ob_end_flush();
flush();
for($i=0; $i<=99; $i++){
echo "Test".$i;
ob_flush();
flush();
sleep(1);
}
return $this->response->setJSON(''); // send empty json response (This is
the most important thing)
}

Related

I want to generate and send multiple responses to client side

I am using Angular for client side and Node and express server for server side and Mongo database..
In my project I want to give some conditions before data to be saved and generate multiple responses as per needed..
I try res.write but give error ..I post my code..In my code I want to send response instead of console.log
router.post('/addratio',(req,res)=>{
var requestbody = req.body.items;
res.setHeader("Content-Type", "text/plain");
// first, convert data into a Map with reduce
let counts = requestbody.reduce((prev, curr) => {
let count = prev.get(curr.Emp_id) || 0;
prev.set(curr.Emp_id, curr.ValueRatio + count);
return prev;
}, new Map());
// then, map your counts object back to an array
let reducedObjArr = [...counts].map(([Emp_id,ValueRatio]) => {
return {Emp_id, ValueRatio}
});
/**/
if(reducedObjArr.length > 0){
AddRatioPickPoint.find({},(err,found)=>{
for(var i=0;i<reducedObjArr.length;i++){
var Empid = reducedObjArr[i].Emp_id;
var Ratio = reducedObjArr[i].ValueRatio;
if(Ratio < 100){
if(found.find(x=>x.Emp_id == Empid)){
var oldRatio = found.find(y=>y.Emp_id == Empid).ValueRatio;
console.log(oldRatio);
if(oldRatio < 100){
var addtion = oldRatio + Ratio;
//console.log(addtion);
if(addtion < 100){
AddRatioPickPoint.updateMany({ "Emp_id":Empid },{$set: { "ValueRatio":addtion}},(err,change)=>{
if(change){
console.log("there is change");
}
})
}
if(addtion == 100){
AddRatioPickPoint.updateMany({ "Emp_id":Empid },{$set: { "ValueRatio":addtion}},(err,change)=>{
if(change){
console.log("there is change");
}
});
EmployeeSchema.updateMany({"_id":Empid},{$set: { "status":false}},(err,change)=>{
if(change){
console.log("there is Emp Status change");
}
});
}
}
}
if(!found.find(x=>x.Emp_id == Empid)){
AddRatioPickPoint.insertMany({Emp_id:Empid,ValueRatio:Ratio},(err,add)=>{
if(add){
console.log("New Addition of reqbody success");
}
});
}
}
if(Ratio == 100){
if(!found.find(t=>t.Emp_id == Empid)){
EmployeeSchema.updateMany({"_id":Empid},{$set: { "status":false}},(err,change)=>{
if(change){
console.log("there is Emp Status change");
}
});
AddRatioPickPoint.insertMany({Emp_id:Empid,ValueRatio:Ratio},(err,add)=>{
if(add){
console.log("New Addition of reqbody success");
}
});
}
if(found.find(t=>t.Emp_id == Empid)){
var oldRatio = found.find(t=>t.Emp_id == Empid).ValueRatio;
console.log(oldRatio);
console.log("not store");
}
}
}
for(var i=0;i<requestbody.length;i++){
var reqEmpID =requestbody[i].Emp_id;
var reqValueRatio = requestbody[i].ValueRatio;
var reqClient = requestbody[i].NameClient;
var reqEmp = requestbody[i].NameEmployee;
var Alldata = {Emp_id:reqEmpID,NameEmployee:reqEmp,NameClient:reqClient,ValueRatio:reqValueRatio};
if(requestbody[i].ValueRatio == 100){
RatioSchema.insertMany(Alldata,(err,add)=>{
if(add){console.log("Ratio data added");}
});
}
if(requestbody[i].ValueRatio < 100){
RatioSchema.insertMany(Alldata,(err,add)=>{
if(add){console.log("Ratio data added");}
})
}
}
})
}
});
You need to use res.send().
if(change){
res.send("there is change");
};
for more information: res.send

How to use KnpPaginatorBundle to paginate results for a search form?

I'm working on a Symfony 2 project and I used KnpPaginatorBundle the first page works correctly but the second one shows me this Error : " The controller must return a response (null given). Did you forget to add a return statement somewhere in your controller? " i didn't understand this please help me
this is my controller:
public function searchAction(Request $request) {
$search_form = $this->createForm(new SearchInterventionBatimentType());
if ($request->isMethod('post')) {
$search_form->handleRequest($request);
if ($search_form->isValid()) {
$data = $search_form->getData();
$from = $data['from'];
$to = $data['to'];
$intervenant= $data['intervenant'];
$type= $data['type'];
$batiment = $data['batiment'];
$em = $this->getDoctrine()->getManager();
$intervention = new InterventionBatiment();
if(is_null($intervenant) && is_null($type) && is_null($batiment)) {
$intervention = $em->getRepository('SecteurBundle:InterventionBatiment')->findByDate($from,$to);
} elseif(is_null($type) && is_null($batiment)) {
$intervention = $em->getRepository('SecteurBundle:InterventionBatiment')->findByDateAndIntervenant($from,$to,$intervenant);
} elseif (is_null($intervenant) && is_null($batiment)) {
$intervention = $em->getRepository('SecteurBundle:InterventionBatiment')->findByDateAndType($from,$to,$type);
} elseif (is_null($intervenant) && is_null($type)) {
$intervention = $em->getRepository('SecteurBundle:InterventionBatiment')->findByDateAndBatiment($from,$to,$batiment);
} elseif (is_null($batiment)) {
$intervention = $em->getRepository('SecteurBundle:InterventionBatiment')->findByDateAndIntervenantAndType($from,$to,$type,$intervenant);
} else {
$intervention = $em->getRepository('SecteurBundle:InterventionBatiment')->findByAll($from,$to,$type,$intervenant,$batiment);
}
$paginator= $this->get('knp_paginator');
$result= $paginator->paginate(
$intervention, /* query NOT result */
$request->query->getInt('page', 1)/*page number*/,
$request->query->getInt('limit', 8)/*limit per page*/
);
return $this->render(
'SecteurBundle:InterventionBatiment:recherche.html.twig',
array('interventions' => $result,'form' => $search_form->createView())
);
}
}
}
the controller should always need to send a response.
In your case you need to send a response if the form is not valid
if ($search_form->isValid()) {
}
return your response here too (if the form is not valid)

Silex - How to pass Request $request to $app->error(function (\Exception $e, $code) use ($app) {

I am new to Silex. I am trying to pass Request $request to $app->error(...){...}. Normally it would look like so:
$app->error(function(\Exception $e, $code) use ($app) { ...
I want to use Request within the error controller. The code below will generate en error. Any idea how to snick the Request $request object into this controller ? so I will have access to request->getPathInfo() ?
//...
$app->error(function(\Exception $e, $code, Request $request) use ($app) {
if (404 === $code) {
$path = $request->getPathInfo();
$path = explode('/',$path);
if($path[1] == 'php'){
return $app->redirect($app['url_generator']->generate('php'));
}
if($path[1] == 'css'){
return $app->redirect($app['url_generator']->generate('css'));
}
//...
return $app->redirect($app['url_generator']->generate('home'));
}
// Do something else (handle error 500 etc.)
});
// RUN
$app->run();
$path = $app['request']->getPathInfo();
$app->error(function(\Exception $e, $code) use ($app) {
if (404 === $code) {
$path = $app['request']->getPathInfo();
$path = explode('/',$path);
echo $path[1];
if($path[1] == 'php'){
return $app->redirect($app['url_generator']->generate('php'));
}
if($path[1] == 'css'){
return $app->redirect($app['url_generator']->generate('css'));
}
//...
return $app->redirect($app['url_generator']->generate('home'));
}
// Do something else (handle error 500 etc.)
});
// RUN
$app->run();
Now I can redirect users when 404 based on the area they are in - to different predefined paths.
$this->error(
function (\Exception $e, Request $request, $code) {
//yours code here
}
);
Try this code,
Request::createFromGlobals()

Codeigniter get random record with limit

I've created a page that load 4 products everytime you scroll down the page with codeigniter and Ajax.
I followed this tutorial for create pagination with codeigniter and jQuery.Everything works fine, moreover I've changed the load type from database using Ajax.
I've got a problem with codeigniter.
When I try to get random record from the table I've got duplicate products.
This is the functions in codeigniter:
UPDATE CONTROLLER
function index()
{
$this->load->helper('url');
$data['description'] = "Description";
$data['keywords'] = "Keywords";
$data['products'] = $this->abitainterni->getAllProductsLimit();
$data['get_products'] = $this->abitainterni->get_products();
$this->load->view('welcome', $data);
}
function get_products($offset)
{
$already_used = $this->input->post('already_used');
$already = explode(',', $already_used);
$data['products'] = $this->abitainterni->getAllProductsLimit($offset, $already);
$arr['view'] = $this->load->view('get_products', $data, true);
$bossy = '';
foreach($data['products'] as $p) {
$bossy .= $p->productID.',';
}
$arr['view'] = $bam;
$arr['ids'] = $bossy;
echo json_encode($arr);
return;
}
UPDATE SCRIPT
<script type="text/javascript">
$(document).ready(function(){
<?
$like_a_boss = "";
foreach($products as $gp):
$like_a_boss .= $gp->productID.',';
endforeach;
?>
var products = '<?= $like_a_boss; ?>';
var loaded_products = 0;
$(".loadMoreProducts").click(function(){
loaded_products += 4;
var dati = "welcome/get_products/" + loaded_products;
$.ajax({
url:'welcome/get_products/' + loaded_products,
type: 'post',
data: {already_used: products},
cache: false,
success: function(data) {
var obj = $.parseJSON(data);
$("#mainContainerProductWelcome").append(obj.view);
already_used += obj.ids;
if(loaded_products >= products - 4) {
$(".loadMoreProducts").hide();
} else {
// load more still visible
}
},
error: function() {
// there's something wrong
}
});
// show spinner on ajax request starts
$(".loading-spinner").ajaxStart(function(){
$(".loading-spinner").show();
$(".text-load").hide();
});
// ajax request complets hide spinner
$(".loading-spinner").ajaxStop(function(){
$(".loading-spinner").delay(5000).hide();
$(".text-load").show();
});
return false;
});
// submit form contact
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
// click on load more btn
$(".loadMoreProducts").click();
return false;
}
});
});
</script>
you'll need to keep track of the products you've already queried, throw their id's in an array, and then use something like a where not in. So something like this:
function getAllProductsLimit($offset=0, $already_used = array(0))
{
$this->db->order_by('productID', 'RANDOM');
$this->db->where_not_in('productID', $already_used);
$query = $this->db->get('product', 4, $offset);
if($query->num_rows() > 0){
return $query->result();
} else {
return 0;
}
}
NEW CONTROLLER
function index()
{
$this->load->helper('url');
$data['title'] = "Scopri i nostri prodotti";
$data['description'] = "Description";
$data['keywords'] = "Keywords";
$data['products'] = $this->abitainterni->getAllProductsLimit();
$data['get_products'] = $this->abitainterni->get_products();
$this->load->view('welcome', $data);
}
function get_products($offset)
{
$already_used = $this->input->post('already_used');
$already = explode(',', $already_used);
$data['products'] = $this->abitainterni->getAllProductsLimit($offset, $already);
$arr['view'] = $this->load->view('get_products', $data, true);
$bossy = '';
foreach($data['products'] as $p)
{
$bossy .= $->productID.',';
}
$arr['view'] = $bam;
$arr['ids'] = $bossy;
echo json_encode($arr);
return;
}
NEW SCRIPT
<script type="text/javascript">
$(document).ready(function(){
<?
$like_a_boss = '';
foreach($get_products as $gp):?>
$like_a_boss .= $gp->productID.',';
endforeach;?>
var products = '<?= $like_a_boss; ?>';
var loaded_products = 0;
$(".loadMoreProducts").click(function(){
loaded_products += 4;
var dati = "welcome/get_products/" + loaded_products;
$.ajax({
url:'welcome/get_products/' + loaded_products,
type: 'post',
data: {already_used: products},
cache: false,
success: function(data) {
var obj = $.parseJSON(data);
$("#mainContainerProductWelcome").append(obj.view);
already_used += obj.ids;
if(loaded_products >= products - 4) {
$(".loadMoreProducts").hide();
} else {
// load more still visible
}
},
error: function() {
// there's something wrong
}
});
// show spinner on ajax request starts
$(".loading-spinner").ajaxStart(function(){
$(".loading-spinner").show();
$(".text-load").hide();
});
// ajax request complets hide spinner
$(".loading-spinner").ajaxStop(function(){
$(".loading-spinner").delay(5000).hide();
$(".text-load").show();
});
return false;
});
// submit form contact
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
// click on load more btn
$(".loadMoreProducts").click();
return false;
}
});
});
</script>
Then whereever your using that function, before you echo out your results to your ajax function, run a quick foreach to add the ids of the products you just got to the already used array. You can either store this is session, or pass it back and forth between your ajax stuff, or if your ajax stuff is written fine, you don't need to worry about it, just attach the product id's to each product you're displaying using a data attribute or something and generate the array that way.

How can I set gzip compression in zend framework website

I am new to zend. I have developed a website using zend framework. Now, I want to set gzip compression in my website. Would you please guide me step wise to implement this.
Thanks in advance.
kamal Arora
There are two methods to gzip output in your website.
Using Webserver.If your webserver is apache you can refer here for a good documentation on how to enable mod_deflate on your server.
Using zend framework. Try the following code which is from this website.
Create a gzip compressed string in your bootstrap file.
Code:
try {
$frontController = Zend_Controller_Front::getInstance();
if (#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
ob_start();
$frontController->dispatch();
$output = gzencode(ob_get_contents(), 9);
ob_end_clean();
header('Content-Encoding: gzip');
echo $output;
} else {
$frontController->dispatch();
}
} catch (Exeption $e) {
if (Zend_Registry::isRegistered('Zend_Log')) {
Zend_Registry::get('Zend_Log')->err($e->getMessage());
}
$message = $e->getMessage() . "\n\n" . $e->getTraceAsString();
/* trigger event */
}
GZIP does not compress images, just the raw HTML/CSS/JS/XML/JSON code from the site being sent to the user.
I made for zend framework 2 (zf2) with your tip
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach("finish", array($this, "compressOutput"), 100);
}
public function compressOutput($e)
{
$response = $e->getResponse();
$content = $response->getBody();
$content = str_replace(" ", " ", str_replace("\n", " ", str_replace("\r", " ", str_replace("\t", " ", $content))));
if(#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)
{
header('Content-Encoding: gzip');
$content = gzencode($content, 9);
}
$response->setContent($content);
}
Honoring the answer of Bruno Pitteli, I think you can compress in the following way:
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'#(?://)?<![CDATA[(.*?)(?://)?]]>#s' //leave CDATA alone
);
$replace = array(
'>',
'<',
'\\1',
"//<![CDATA[n".'1'."n//]]>"
);
$content = preg_replace($search, $replace, $content);
So the full code sample now looks like:
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach("finish", array($this, "compressOutput"), 100);
}
public function compressOutput($e)
{
$response = $e->getResponse();
$content = $response->getBody();
$content = preg_replace(array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', '#(?://)?<![CDATA[(.*?)(?://)?]]>#s'), array('>', '<', '\\1', "//<![CDATA[n".'1'."n//]]>"), $content);
if (#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
header('Content-Encoding: gzip');
$content = gzencode($content, 9);
}
$response->setContent($content);
}