I have below code to get more results on page scroll.
It works fine on localhost and on server laptop/desktop.
It does not work on mobile and does not load more results on scroll.
I cannot figure it out why this is happening or what is causing this not to work on mobile.
<?php
$getItemLID = $dba->prepare('SELECT MAX(id) as id FROM items
where status = ? AND ename like ?');
$getItemLID->bind_param('ss', $status,$param);
$getItemLID->execute();
$resultLID = $getItemLID->get_result();
$rowLID = $resultLID->fetch_assoc();
$thelastid = $rowLID['id'];
$status = 1;
$getscategory = $dba->prepare('SELECT * FROM mytable
where status = ?
order by id asc');
$getscategory->bind_param('s', $status);
$getscategory->execute();
$resultGSC = $getscategory->get_result();
while ($rowGSC = $resultGSC->fetch_assoc()) {
$scid = $rowGSC['id'];
$scename = $rowGSC['ename'];
?>
<div class="message_box" data-id="<?php echo $scid; ?>" style="padding-right: 5px;">
<div class="portfolio-item-wrap" style="border-radius: 3%;">
<span class="portfolio-description">
<h3><?php echo $scename; ?></h3>
</span>
</div>
</div>
<?php } ?>
<div id="msg_loaderw" style="display: none;">
<div class="card">
<div class="card-body">
<div class="d-flex align-items-center">
<strong>Loading...</strong>
<div class="spinner-border ml-auto" role="status" aria-hidden="true">
</div>
</div>
</div>
</div>
</div>
<div id="msg_loader">
</div>
<script>
$(document).ready(function () {
$(window).scroll(function () {
var thislastid = "<?php echo $thelastid; ?>";
if($(window).scrollTop() == ($(document).height() - $(window).height())) {
$("#msg_loaderw").show();
var msg_id = $(".message_box:last").data("id");
$.ajax({
type: "POST",
url: "inc/items/search_items_get.php",
data: {msg_id: msg_id},
cache: false,
success: function (data) {
//Insert data after the message_box
$(".message_boxx").append(data);
if (msg_id == thislastid) {
$("#msg_loaderw").hide();
$("#msg_loader").html('<hr><div class="card"><div class="card-body"><div class="align-items-center"><strong><center>That is all what we have for now.</center></strong></div></div></div>');
}
}
});
}
});
});
</script>
Below is : inc/items/search_items_get.php
<?php
include ('../default/db.php');
if (isset($_POST['msg_id']) && isset($_POST['msg_id']) !== NULL) {
$msg_id = $_POST['msg_id'];
$status = 1;
$limit = 12;
$getItem = $dba->prepare('SELECT * FROM mytable
where id > ? AND status = ?
order by id asc');
$getItem->bind_param('ss', $msg_id,$status);
$getItem->execute();
$resultItem = $getItem->get_result();
while ($rowItem = $resultItem->fetch_assoc()) {
$itemID = $rowItem['id'];
$itemName = $rowItem['ename'];
?>
<div class="message_box" data-id="<?php echo $itemID; ?>" style="padding-right: 5px;">
<div class="portfolio-item-wrap" style="border-radius: 3%;">
<span class="portfolio-description">
<h5><?php echo $itemName; ?></h5>
</span>
</div>
</div>
<?php
}
} else {
echo "Message ID is empty";
}
?>*emphasized text*
It seems it's a script issue just try changing the code a bit , hopefully it will work:
<script>
$(document).ready(function () {
$(window).scroll(function () {
var scrollHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
$("#msg_loaderw").show();
var msg_id = $(".message_box:last").data("id");
$.ajax({
type: "POST",
url: "inc/items/search_items_get.php",
data: {msg_id: msg_id},
cache: false,
success: function (data) {
//Insert data after the message_box
$(".message_boxx").append(data);
if (msg_id == thislastid) {
$("#msg_loaderw").hide();
$("#msg_loader").html('<hr><div class="card"><div class="card-body"><div class="align-items-center"><strong><center>That is all what we have for now.</center></strong></div></div></div>');
}
}
});
}
});
});
</script>
I'm relatively new to the world of programming and this is my first question on stack overflow. I have to create a system written in php and jquery that allows to order a series of images and, based on the order, create a banner-style animation. The only problem is that when the script selects the images from the div to create the animation they disappear. thanks in advance for your collaboration
the javascript
$(document).ready(function () {
const images = document.querySelectorAll('.imgw');
$('#preview').html(images[0]);
$("#genera").click(function () {
setInterval(banner, 2500);
var index = 1;
});
});
const banner = () => $('#preview').fadeOut('slow', function () {
$(this).html(images[index]);
$(this).fadeIn('slow', function () {
if (index == images.length - 1) {
index = 0;
} else {
index++;
}
});
})
the html file
<section>
<div class="row" style="margin-top:25px;">
<div class="col text-center">
<h2 style="margin-top:25px;">Anteprima</h2>
<div id="preview">
</div>
</div>
</div>
</section>
<section>
<div class="row" id="slides" style="margin-top:25px;">
<div class="col text-center">
<!-- <div id="box"> -->
<h2 style="margin-top:25px;">Slides</h2>
<ul id="sortable">
<?php
$html = "";
$count = 1;
foreach ($images as $img) {
$url = $img["url"];
$size = $img["size"];
$humanSize = $img["human_size"];
$html .= "\t\t<img src='{$url}' class='imgw' id='{$count}' alt='image_{$count}' />\n";
$count++;
}
echo $html;
?>
</ul>
</div>
I read the documentation better and solved the problem
the javascript
var images = $('.ui-sortable').children("img").clone();
var index = 1;
const banner = () => $('#anteprima').fadeOut('slow', function () {
$(this).html(images[index]);
$(this).fadeIn('slow', function () {
if (index == images.length - 1) {
index = 0;
} else {
index++;
}
});
})
setInterval(banner, 2500);
I am working on a project which is cropping uploaded image in circle and then save it for preview. Here is also a button for download saved image which is cropped.
Here is my main php page:
<html lang="en">
<head>
<title>PHP - jquery ajax crop image before upload using croppie plugins</title>
<script src="http://demo.itsolutionstuff.com/plugin/jquery.js"></script>
<script src="http://demo.itsolutionstuff.com/plugin/croppie.js"></script>
<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/bootstrap-3.min.css">
<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/croppie.css">
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Image Cropping Area</div>
<div class="panel-body">
<div class="row">
<div class="col-md-4 text-center">
<div id="upload-demo" style="width:350px"></div>
</div>
<div class="col-md-4" style="padding-top:30px;">
<strong>Select Image:</strong>
<br/>
<input type="file" id="upload">
<br/>
<button class="btn btn-success upload-result">Upload Image</button>
</div>
<div class="col-md-4" style="">
<div id="upload-demo-i" style="background:#e1e1e1;width:300px;padding:30px;height:300px;margin-top:30px"></div>
</div>
<div>
<a name="Download Save Image" id="download" download>Download Save Image</a>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$uploadCrop = $('#upload-demo').croppie({
enableExif: true,
viewport: {
width: 200,
height: 200,
type: 'circle'
},
boundary: {
width: 300,
height: 300
}
});
$('#upload').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
$uploadCrop.croppie('bind', {
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "ajaxpro.php",
type: "POST",
data: {"image":resp},
success: function (data) {
console.log(data);
var response = JSON.parse(data);
if (response.image) {
html = '<img id="preview" src="' + response.image + '" />';
$("#upload-demo-i").html(html);
$('#download').attr({
target: '_blank',
href: response.image
})
}else {
alert('Failed to upload image');
}
}
});
});
});
</script>
</body>
</html>
and the other for ajax is:
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
if (file_put_contents('upload/' . $imageName, $data)) {
echo json_encode(['image' => 'upload/' . $imageName]); // upload is successful and we return image URL to Javascript
}else {
echo json_encode(['image' => false]); // if upload fails
}
Its functionality is simple and working well.I tried hard to make a simple downloadable button but never found suitable JQuery. Now I am looking for JQuery for my download button to download cropped image. Kindly guide me what part of code I have to put and where.
Thanks for the help. :)
I have changed your Download image button to <a> and given it an id of download and used HTML5 download attribute to force file download
<div>
<a name="Download Save Image" id="download" download>Download Save Image</a>
</div>
Your PHP
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
if (file_put_contents('upload/' . $imageName, $data)) {
echo json_encode(['image' => 'upload/' . $imageName]); // upload is successful and we return image URL to Javascript
}else {
echo json_encode(['image' => false]); // if upload fails
}
Then in your AJAX get the image URL and set it to the download anchor tag by adding the href and target attributes.
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "ajaxpro.php",
type: "POST",
data: {"image": resp},
success: function (data) {
console.log(data);
var response = JSON.parse(data);
if (response.image) {
html = '<img id="preview" src="' + response.image + '" />';
$("#upload-demo-i").html(html);
$('#download').attr({
target: '_blank',
href: response.image
})
}else {
alert('Failed to upload image');
}
}
});
});
});
We are using jquery.fileApi.js to upload images in a form alongwith Yii Framework. https://rubaxa.github.io/jquery.fileapi/
We have successfully uploaded the images on the server.
Here's the code to upload a file,
<script>
var examples = [];
var imageNames = [];
</script>
<div id="multiupload">
<form class="b-upload b-upload_multi" action="<?php echo $this->createUrl('item/sellNow') ?>" method="POST" enctype="multipart/form-data">
<div class="whiteBox clearfix" id="mulUplImgParent" style="display: none;">
<ul id="sortable" class="js-files b-upload__files">
<li class="col-xs-6 col-sm-2 col-md-2 js-file-tpl b-thumb" data-id="<%=uid%>" title="<%-name%>, <%-sizeText%>">
<header class="clearfix">
<div data-fileapi="file.remove" class="b-thumb__del pull-left"></div>
<% if( /^image/.test(type) ){ %>
<div data-fileapi="file.rotate.cw" class="b-thumb__rotate pull-right"></div>
<% } %>
</header>
<div class="b-thumb__preview">
<div class="b-thumb__preview__pic"></div>
</div>
</li>
</ul>
</div>
<div class="form-group">
<div id="uploadMulImgBtn" class="btn btn-pink btn-small js-fileapi-wrapper">
<span>Browse Images</span>
<input type="file" name="filedata" />
</div>
<figure class="note"><strong>Hint:</strong> You can upload all images at once!</figure>
</div>
</form>
<script type="text/javascript">
examples.push(function() {
$('#multiupload').fileapi({
multiple: true,
url: '<?php echo $this->createUrl('item/uploadImage') ?>',
paramName: 'filedata',
duplicate: false,
autoUpload: true,
onFileUpload: function(event, data) {
imageNames.push(data.file.name);
$("#item-images").val(imageNames.join(','));
},
onFileRemoveCompleted: function(event, data) {
var removeItem = data.name;
imageNames = jQuery.grep(imageNames, function(value) {
return value != removeItem;
});
$("#item-images").val(imageNames.join(','));
},
elements: {
ctrl: {upload: '.js-upload'},
empty: {show: '.b-upload__hint'},
emptyQueue: {hide: '.js-upload'},
list: '.js-files',
file: {
tpl: '.js-file-tpl',
preview: {
el: '.b-thumb__preview',
width: 80,
height: 80
},
upload: {show: '.progress', hide: '.b-thumb__rotate'},
complete: {hide: '.progress'},
progress: '.progress .bar'
}
}
});
});
</script>
</div>
Server Side Code
public function actionUploadImage(){
$userId = Yii::app()->user->id;
$tmpFilePath = $_FILES['filedata']['tmp_name'];
$imageName = $_FILES['filedata']['name'];
$path = 'user_files/';
if(is_dir($path))
{
$dir = $path.$userId;
if(!is_dir($dir))
{
mkdir($dir,0777);
}
$subDir = $dir . '/temp';
if(!is_dir($subDir))
{
mkdir($subDir,0777);
}
$imagePath = "$subDir/$imageName";
move_uploaded_file($tmpFilePath, "$subDir/$imageName");
$image = new Image($imagePath);
$image->resize(190, 190);
$image->save();
$jsonResponse = array('imageName' => $imageName,'imagePath' => $imagePath);
echo CJSON::encode($jsonResponse);
}
//var_dump($_FILES);
//var_dump($_POST);die;
}
We are having issues how to load those images again on the form.
We want to show uploaded images on edit form along with all the event handlers bind through jquery.fileApi .
We cant figure out a way which could render already uploaded images.
Thanks,
Faisal Nasir
so im my zend framework aplication and im trying to set the view sucess var to true in order to show a sucess messega.
so in my choosetags.phtml ive got this
<script language = "Javascript">
$(document).ready(function() {
$("#button").click(function () {
var param1 = 'first'; //or get value from some DOM element
var param2 = 'second'; //or get value from some DOM element
$.ajax({
url: '/rondas/saveronda',
type: 'POST',
data: {param1: param1, param2:param2 },
datatype: "json"
});
});
});
</script>
<?php if($this->success): ?>
<div class="albox succesbox" style="z-index: 690;">
<b>Sucesso :</b> A Palavra-passe foi alterada com sucesso.
</div>
<?php endif; ?>
<?php if($this->hasError): ?>
<div class="albox errorbox" style="z-index: 690;">
<b>Erro :</b> <?php echo $this->errorMessage; ?>
</div>
<?php endif; ?>
<div class="simplebox grid740" style="z-index: 500;">
<div class="titleh" style="z-index: 400;">
<h3>Criar Ronda</h3>
</div>
<div class="body" style="z-index: 380;">
<script type="text/javascript">
var t=0;
$(function(){
$("#toolbar").jqGrid({
caption:"Tags",
colNames:['ID','Nome','Cliente','Descrição','Modo','Estado'],
colModel:[
{name:'id_tag',index:'id_tag',hidden:true},
{name:'tag_nome',index:'tag_nome'},
{name:'nome',index:'nome'},
{name:'descricao',index:'descricao'},
{name:'modo',index:'modo'},
{name:'estado',index:'estado'}
],
datatype:"json",
height:421,
rownumWidth:40,
pager:'#ptoolbar',
rowList:[10,20,30],
rowNum:10,
sortname:'id_tag',
sortorder:'desc',
viewrecords:true,
width:700
});
$("#toolbar").jqGrid('navGrid','#ptoolbar',{del:false,add:false,edit:false,search:false});
$("#toolbar2").jqGrid({
caption:"Tags da Ronda",
colNames:['ID','Nome','Cliente','Descrição','Modo','Estado'],
colModel:[
{name:'id_tag',index:'id_tag',hidden:true},
{name:'tag_nome',index:'tag_nome'},
{name:'nome',index:'nome'},
{name:'descricao',index:'descricao'},
{name:'modo',index:'modo'},
{name:'estado',index:'estado'}
],
datatype:"json",
height:421,
rownumWidth:40,
pager:'#ptoolbar2',
rowList:[10,20,30],
rowNum:10,
sortname:'id_tag',
sortorder:'desc',
viewrecords:true,
width:700
});
$("#toolbar2").jqGrid('navGrid','#ptoolbar2',{del:false,add:false,edit:false,search:false});
$("#toolbar").jqGrid('gridDnD',{connectWith:'#toolbar2',dragcopy:true,beforedrop: function (ev, ui, getdata, $source, $target) {
var names = $target.jqGrid('getCol', 'id_tag');
if ($.inArray(getdata.id_tag, names) >= 0) {
// prevent data for dropping
ui.helper.dropped = false;
alert("A tag ja existe na ronda");
}
else
{
document.getElementById("tagini").innerHTML= document.getElementById("tagini").innerHTML +"<option value="+getdata.id_tag+">"+getdata.tag_nome+','+getdata.nome+','+getdata.descricao+','+getdata.modo+"</option>";
document.getElementById("tagfim").innerHTML= document.getElementById("tagfim").innerHTML +"<option value="+getdata.id_tag+">"+getdata.tag_nome+','+getdata.nome+','+getdata.descricao+','+getdata.modo+"</option>"; }}});
});
$(function(){
// Attach the dynatree widget to an existing <div id="tree"> element
// and pass the tree options as an argument to the dynatree() function:
$("#tree").dynatree({
initAjax: {
url: "/locais/tree"
},
onActivate: function(node) {
t=node.data.key;
if(t!=0)
{
$("#echoActive").text(node.data.title);
$("#tables").show();
$("#toolbar").jqGrid('setGridParam',{url:"/rondas/choosetags/id/"+t}).trigger("reloadGrid");
reloadGrid();
}
else
{
$("#echoActive").text("-");
$("#tables").hide();
}
}
});
});
</script>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Escolher a localização:</span>
<div id="tree" > </div>
<div class="clear" style="z-index: 670;"></div>
</div>
<!-- Add a <div> element where the tree should appear: -->
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Localização:<span id="echoActive">-</span></span>
<div id="tables" style="display:none" >
<table id="toolbar"></table>
<div id="ptoolbar"></div>
</div>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tags da ronda:</span>
<table id="toolbar2"></table>
<div id="ptoolbar2"></div>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Nome da ronda:</span>
<input type="text" name="nomeronda" id="nomeronda">
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tag Inicial:</span>
<select id="tagini" name="tagini">
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tag Final:</span>
<select id="tagfim" name="tagfim">
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Ordem:</span>
<select id="ordem" name="ordem">
<option value="Sim">Sim</option>
<option value="Não">Não</option>
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="button-box" style="z-index: 460;">
<input id="button" class="st-button" type="submit" value="Submit" name="button">
<input id="button2" class="st-clear" type="reset" value="Cancel" name="button">
</div>
</div>
</div>
so the user choose when the user press submit data it makes an ajax call to /rondas/saveronda, in this action i will save the data on the database, and once it succeds i want to redirect to the /rondas/chooserondas and show a sucess message, how can i achieve this..
so here is the code for the /rondas/saveronda
public function saverondaAction()
{
// action body
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if($this->_request->isXmlHttpRequest())
{
$param1 = $this->_request->getParam('param1');
$param2 = $this->_request->getParam('param2');
//save data on the db and return to the /rondas/choosetags and display sucess message.
}
}
and here is the code for the /rondas/choosetags
public function choosetagsAction()
{
// action body
if($this->_request->isXmlHttpRequest())
{
$request= $this->getRequest();
$poll_id = $request->getParam('id');
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
Zend_Paginator::setDefaultScrollingStyle('Sliding');
$page = $this->_getParam('page', 1);
$limit = $this->_getParam('rows', 0);
$sidx = $this->_getParam('sidx', 1);
$sord = $this->_getParam('sord', 0);
$totalrows = $this->_getParam('totalrows', false);
if($totalrows)
$limit = $totalrows;
$tableModel = new Application_Model_Tags();
$select = $tableModel->select();
$select->setIntegrityCheck(false);
$select->from('tags', array('id_tag','tag_nome', 'id_software', 'id_hardware','id_localizacao','descricao','modo','estado'))->joinInner('clientes', 'tags.id_cliente = clientes.id_cliente', array('nome'))->where('id_localizacao='.$poll_id);
$filters = !empty($_REQUEST['filters']) ? (array) json_decode($_REQUEST['filters']) : array();
$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
$paginator = new Zend_Paginator($adapter);
$paginator->setCurrentPageNumber($page)->setItemCountPerPage($limit);
$count = $paginator->getTotalItemCount();
$total_pages = $count > 0 ? ceil($count / $limit) : 1;
$responce = new stdClass();
$responce->page = $page > $total_pages ? $total_pages : $page;
$responce->total = $total_pages;
$responce->records = $count;
$i = 0;
foreach($paginator as $item)
{
$responce->rows[$i]['id'] = $item['id_tag'];
$responce->rows[$i]['cell'] = array($item['id_tag'],$item['tag_nome'],$item['nome'],$item['descricao'],$item['modo'],$item['estado']);
$i++;
}
echo json_encode($responce);
} else
{
$this->_helper->layout()->pageTitle = 'Rondas';
$this->_helper->layout()->pageDescription = 'Criar as rondas';
}
}
i can show the message if i am on the same action and view , i mean , in the /rondas/choosetags if i put this $this->view->sucess=true, the success message apperas, but i want to set the success var to true in action /rondas/saveronda and then redirect to the action /rondas/choose tags and show success message.
You can't directly. What you can do is save the params you want to set in a temporary session (with a expiration of, for example, 1 hop = 1 successful request):
$hopSession = new Zend_Session_Namespace('tempViewParams');
$hopSession->my_view_param1 = 'string with data';
$hopSession->setExpirationHops(1);
You can than get the values from your temporary session in the next action.
Another way is to add the view values you want to set as params in the url you're redirecting to on a successful save (especially in this case where all you want is a true param). So an url like:
/rondas/choosetags/sucess/1
So you can add something to your choosetagsAction() like:
if(1 == $request->getParam('success'))( {
$this->view->success = true;
}
Of course in case you want to pass through multiple params the SESSION solution would be the most beautiful.