I am facing a problem in accessing the value of hidden field.
I have made an image cropping application in which i am asking the user to upload an image and a UI is provided to help the user to select the area to crop. Then the top left x and y coordinate and the width and height of the selected area is stored as a semicolon separated string in a hidden input field and when the 'Crop' button is clicked the image and the hidden filed value is passed to the crop.php file. But the values of the hidden field is not accessible in the php file.
My html file which provides browse and crop functionality -
<!doctype html>
<html>
<head>
<title>
Crop
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="scripts/jquery.imgareaselect.pack.js"></script>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/imgareaselect-default.css" />
<script>
var app = angular.module('main-App',[]);
app.controller('AdminController', function($scope, $http) {
$scope.form = [];
$scope.files = [];
$scope.progressBar=0;
$scope.progressCounter=0;
$scope.submit = function() {
alert('Sub');
$scope.form.image = $scope.files[0];
$http({
method : 'POST',
url : 'crop.php',
processData: false,
transformRequest: function (data) {
var formData = new FormData();
formData.append("image", $scope.form.image);
return formData;
},
data : $scope.form,
headers: {
'Content-Type': undefined
},
uploadEventHandlers: {
progress: function (e) {
if (e.lengthComputable) {
$scope.progressBar = (e.loaded / e.total) * 100;
$scope.progressCounter = $scope.progressBar;
$("#completion").css("width", $scope.progressBar+'%');
}
}
}
}).then(function successCallback(response) {
alert($scope.form.params);
});
};
$scope.uploadedFile = function(element) {
$scope.currentFile = element.files[0];
var reader = new FileReader();
reader.onload = function(event) {
$scope.image_source = event.target.result
$scope.$apply(function($scope) {
$scope.files = element.files;
});
}
reader.readAsDataURL(element.files[0]);
$('img#photo').imgAreaSelect({
onSelectStart: {enable:true},
onSelectEnd: function (img, selection) {
document.getElementById("params").value=selection.x1+';'+selection.y1+';'+selection.width+';'+selection.height;
alert(document.getElementById("params").value);
}
});
}
});
</script>
<style>
html,body {
height: 100%;
}
.wrapper{
height:auto;
}
.wrapper img {
height:100%;
color:grey;
text-align: center;
line-height:100px;
vertical-align: middle;
padding:0px;
margin:0px;
}
</style>
</head>
<body>
<div ng-app="main-App" ng-controller="AdminController">
<form ng-submit="submit()" name="form" role="form" enctype="multipart/form-data">
<div class="container-fluid">
<div class="row flex-items-xs-center">
<div class="col-md-9">
<div class="container-fluid">
<div class="row">
<div class="col-md-9">
<div class="wrapper">
<img id="photo" name="photo" src="{{image_source}}" alt="Image preview..." class="img-responsive img-thumbnail" style="border-style:dashed">
</div>
</div>
</div>
</div>
<br/>
<br/>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<label class="btn btn-primary">
<input ng-model="form.image" type="file" class="form-control input-lg" name="image" id="image"
accept = "image/*"
onchange="angular.element(this).scope().uploadedFile(this)"
style="display:none;" >
<span class="glyphicon glyphicon-folder-open"></span>
Browse
</label>
</div>
<div class="col-md-2">
<label class="btn btn-success">
<input type="submit" id="submit" value="Submit" style="display:none;"/>
<span class="glyphicon glyphicon-cloud-upload"></span>
Crop
</label>
</div>
</div>
</div>
</div>
</div>
</div>
<input type="hidden" name="params" id="params" value="0;0;0;0" ng-model="params" />
</form>
<br/>
<br/>
<div class="container-fluid">
<div class="row">
<div class="col-md-9">
<div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" id ="completion" name="completion"
aria-valuenow="0" aria-valuemin="0" aria-valuemax="50" style="width:0%;height:10px;border-width:0px;border-radius:2px;">
</div>
</div>
</div>
</div>
</div>
<br/>
<br/>
the UI -
crop.php -
<?php
$uncropped_path = '/var/www/html/images/original/';
$cropped_path = '/var/www/html/images/cropped/';
if(isset($_FILES['image'])){
//$ext = pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION);
$image = $_FILES['image']['name'];
move_uploaded_file($_FILES["image"]["tmp_name"], $uncropped_path.$image);
$data = json_decode(file_get_contents("php://input"));
print_r($data);
}else{
echo "Image Is Empty";
}
function doResize($filename,$size,$resize_path)
{
$image = new Imagick();
$file = file_get_contents($filename);
$image->readImageBlob($file);
$dimensions = $image->getImageGeometry();
$pathInfo = pathinfo($filename);
$name = $pathInfo['filename'];
$srcWidth = $dimensions['width'];
$srcHeight = $dimensions['height'];
list($resWidth,$resHeight) = getResizeDim($size,$srcWidth,$srcHeight);
$image->resizeImage($resWidth,$resHeight,Imagick::FILTER_LANCZOS,.85);
$image->writeImage($resize_path);
}
function getResizeDim($size,$srcWidth,$srcHeight)
{
$width;
$height;
if($srcHeight > $srcWidth)
{
if($srcHeight > $size)
$height = $size;
else $height = $srcHeight;
$width = ceil($height*($srcWidth/$srcHeight));
}
else {
if($srcWidth > $size)
$width = $size;
else $width = $srcWidth;
$height = ceil($width*($srcHeight/$srcWidth));
}
return array($width,$height);
}
When i try to print the data received in php i get the following -
Moreover the data array in the php seems to be empty.
I have read various similar questions on stackoverflow but none of them worked in my case.
Related
after I post it use ajax,the value of radio disappear,but I want the radio part to remember the selection. I need the page to remember the radio button selections when I leaves and returns. Would this require database? If so, how do i implement it? I try to add the select =selected ,but it do not help.
<input value="<?php echo $key; $key++;?>" type="radio" class="radioOrCheck" name="answer<?php echo $num_select;?>"
id="0_answer_<?php echo $num_select;?>_option_<?php echo $key;?>"
below it is the full code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
<link href="css/iconfont.css" rel="stylesheet" type="text/css" />
<link href="css/test.css" rel="stylesheet" type="text/css" />
<style>
.hasBeenAnswer {
background: #5d9cec;
color:#fff;
}
</style>
</head>
<body>
<p>
</p>
<div class="main">
<!--nr start-->
<div class="test_main">
<div class="nr_left">
<div class="test">
<form action="" method="post">
<div class="test_title">
<!--
<p class="test_time">
<i class="icon iconfont"></i><b class="alt-1">01:40</b>
</p>-->
<font><?php echo "<input type='button' name='test_jiaojuan' value='sub' onClick='getinput($ans_json,$id_json)'>";?>
</font>
</div>
<div class="test_content">
<div class="test_content_title">
<h2>word</h2>
<p>
<span>has</span><i class="content_lit"><?php echo $cnt_sel;?></i><span>title</span><span>sum</span><i class="content_fs"><?php echo $cnt_sel*10;?></i><span>min</span>
</p>
</div>
</div>
<div class="test_content_nr">
<ul>
<!--begin select-->
<?php
foreach($results as $temp){
$sql_2="SELECT `description`,`input`,`select_id` FROM `select` WHERE `select_id`=?";
$res_2=pdo_query($sql_2,$temp[0]);
$row = $res_2[0];
?>
<li id="qu_0_<?php echo $num_select;?>">
<div class="test_content_nr_tt">
<i><?php echo $num_select;?></i><font>
<p>
<?php
echo $row[0];
?>
</p>
</font>
</div>
<div class="test_content_nr_main">
<ul>
<?php
if ($row[1]) {
$arr = rtrim($row[1],"<br />");
$arr = explode('<br />', $arr);
foreach($arr as $key => $a){
?>
<li class="option">
<input value="<?php echo $key; $key++;?>" type="radio" class="radioOrCheck" name="answer<?php echo $num_select;?>"
id="0_answer_<?php echo $num_select;?>_option_<?php echo $key;?>"
/>
<label for="0_answer_<?php echo $num_select;?>_option_<?php echo $key;?>">
<p class="ue" style="display: inline;"><?php echo strip_tags($a,"<img>");//echo trim($a); ?></p>
</label>
</li>
<?php
}
}
if ($row['hint']) {
?><h4><?php echo $MSG_HINT;?></h4><?php
echo $row['hint'];
}
?>
</ul>
</br></br>
</div>
</li>
<?php
$num_select=$num_select+1;
}
?>
<p>
<?php
?>
</p>
<!--end select-->
</ul>
</div>
</form>
</div>
</div>
<div class="nr_right">
<div class="nr_rt_main">
<div class="rt_nr1">
<div class="rt_nr1_title">
<h1>
<i class="icon iconfont"></i>answer
</h1>
<!-- <p class="test_time">
<i class="icon iconfont"></i><b class="alt-1">01:40</b>
</p>-->
</div>
<div class="rt_content">
<div class="rt_content_tt">
<h2>chose</h2>
<p>
<span>sum</span><i class="content_lit"><?php echo $cnt_sel;?></i><span>answer</span>
</p>
</div>
<div class="rt_content_nr answerSheet">
<ul>
<?php
$temp=1;
for($temp=1;$temp<=$cnt_sel;$temp++){
?>
<li><?php echo $temp;?></li>
<?php
}
?>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<!--nr end-->
<div class="foot"></div>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery.easy-pie-chart.js"></script>
<script src="js/jquery.countdown.js"></script>
<script>
$(function() {
$('li.option label').click(function() {
debugger;
var examId = $(this).closest('.test_content_nr_main').closest('li').attr('id');
var cardLi = $('a[href=#' + examId + ']');
if(!cardLi.hasClass('hasBeenAnswer')){
cardLi.addClass('hasBeenAnswer');
}
});
});
$(function() {
$('li.option').click(function() {
debugger;
var examId = $(this).closest('.test_content_nr_main').closest('li').attr('id');
var cardLi = $('a[href=#' + examId + ']');
if(!cardLi.hasClass('hasBeenAnswer')){
cardLi.addClass('hasBeenAnswer');
}
});
});
/*window.onbeforeunload = function(event){
var msg = '';
msg +='do not like?\n';
//msg += '';
return msg;
};*/
function getinput(ans_json,results_json) {
var sum=<?php echo $cnt_sel;?>;
var blank_cnt=0;
var well_cnt=0;
for (var i = 1; i <= sum; i++) {
var radio_name = new String("answer" + i.toString());
var ans_s = $('input:radio[name=' + radio_name + ']:checked').val();
if(!(ans_s)){
blank_cnt++;
}}
//var json = getjson();
var msg = "ok";
if (confirm(msg) == true) {
var radio = new Array();
for (var i = 1; i <= <?php echo $cnt_sel;?>; i++) {
var radio_name = new String("answer" + i.toString());
var ans_s = $('input:radio[name=' + radio_name + ']:checked').val();
if(!(ans_s)){
ans_s=-1;
}
var judge=0;
var answer_true= parseInt(ans_json[i-1]);
var id_true=parseInt(results_json[i-1]);
if(ans_s == answer_true){
judge=1;
}
$.ajax({
type: "GET",
url: "select_ajax.php",
data: {
select_id: id_true,
contest_id:<?php echo $cid;?>,
result:judge
},
success: function(msg){
well_cnt++;
}
});
}
if(well_cnt==5){
alert('success');
}
setTimeout(function (){
window.location.href = "contest.php?cid="+<?php echo $cid;?>;
}, 1000);
} else {
return false;
}
}
</script>
</body>
</html>
You can do it by storing your radio button value in javascript localStorage and then set that localStorage value to your radio button again.
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.
I am new to PHP and JEasy UI.
I am actually running the demo application of JEasy UI Grid.
Whereas I am not getting the data from Php file to Grid.
Any Idea or suggestion please...!!
Below is My Code:
index.php
<html>
<head>
<meta charset="UTF-8">
<title>Basic CRUD Application - jQuery EasyUI CRUD Demo</title>
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
</head>
<body>
<div class="demo-info" style="margin-bottom:10px">
<div class="demo-tip icon-tip"> </div>
</div>
<table id="dg" title="My Users" class="easyui-datagrid" style="width:700px;height:250px"
url="http://www.jeasyui.com/tutorial/app/crud/get_users.php"
toolbar="#toolbar" pagination="true"
rownumbers="true" fitColumns="true" singleSelect="true">
<thead>
<tr>
<th field="firstname" width="50">First Name</th>
<th field="lastname" width="50">Last Name</th>
<th field="phone" width="50">Phone</th>
<th field="email" width="50">Email</th>
</tr>
</thead>
</table>
<div id="toolbar">
New User
Edit User
Remove User
</div>
<div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"
closed="true" buttons="#dlg-buttons">
<div class="ftitle">User Information</div>
<form id="fm" method="post" novalidate>
<div class="fitem">
<label>First Name:</label>
<input name="firstname" class="easyui-validatebox" required="true">
</div>
<div class="fitem">
<label>Last Name:</label>
<input name="lastname" class="easyui-validatebox" required="true">
</div>
<div class="fitem">
<label>Phone:</label>
<input name="phone">
</div>
<div class="fitem">
<label>Email:</label>
<input name="email" class="easyui-validatebox" validType="email">
</div>
</form>
</div>
<div id="dlg-buttons">
Save
Cancel
</div>
<script type="text/javascript">
var url;
function newUser(){
$('#dlg').dialog('open').dialog('setTitle','New User');
$('#fm').form('clear');
url = 'save_user.php';
}
function editUser(){
var row = $('#dg').datagrid('getSelected');
if (row){
$('#dlg').dialog('open').dialog('setTitle','Edit User');
$('#fm').form('load',row);
url = 'update_user.php?id='+row.id;
}
}
function saveUser(){
$('#fm').form('submit',{
url: url,
onSubmit: function(){
return $(this).form('validate');
},
success: function(result){
var result = eval('('+result+')');
if (result.errorMsg){
$.messager.show({
title: 'Error',
msg: result.errorMsg
});
} else {
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
}
}
});
}
function destroyUser(){
var row = $('#dg').datagrid('getSelected');
if (row){
$.messager.confirm('Confirm','Are you sure you want to destroy this user?',function(r){
if (r){
$.post('destroy_user.php',{id:row.id},function(result){
if (result.success){
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({ // show error message
title: 'Error',
msg: result.errorMsg
});
}
},'json');
}
});
}
}
</script>
<style type="text/css">
#fm{
margin:0;
padding:10px 30px;
}
.ftitle{
font-size:14px;
font-weight:bold;
padding:5px 0;
margin-bottom:10px;
border-bottom:1px solid #ccc;
}
.fitem{
margin-bottom:5px;
}
.fitem label{
display:inline-block;
width:80px;
}
</style>
</body>
</html>
PHP Code URL
http://www.jeasyui.com/tutorial/app/crud/get_users.php
to get the data from datagrid you need to code like this
public function get_user(){
/*Default request pager params from jeasyUI*/
$offset = isset($_POST['page']) ? intval($_POST['page']) : 1;
$limit = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$search = isset($_POST['search']) ? $_POST['itemid'] : '';
$offset = ($offset-1)*$limit;
//change this line to yours
$data = $this->user_model->get_user($offset,$limit,$search);
$i = 0;
$rows = array();
foreach ($data ['data'] as $r) {
$rows[$i]['first_name'] = $r->first_name;
$rows[$i]['last_name'] = $r->last_name;
$rows[$i]['phone'] = $r->phone;
$rows[$i]['email'] = $r->email;
$i++;
}
//keys total & rows is required on jEasyUI
$result = array('total'=>$data['count'],'rows'=>$rows);
echo json_encode($result);
}
more complete example here
I have a problem I've been trying to solve for the past days. I have a Jquery that updates an HTML and creates new content inside a div tag. The thing is that the javascript does not apply on the generated code. In other words, I could take the exact output that the Php gives me, put it in the html code directly and it works, but if it comes from the php while the page is running it won't work, it doesn't display the images correctly in a slideshow jflow.
Here is the HTML header
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script src="js/jquery.robwalsh.randomImageOnload.js" type="text/javascript" charset="utf-8"></script>
<script src="js/application.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.flow.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("div#controller").jFlow({
slides: "#slides",
width: "785px",
height: "480px"
});
});
</script>
<script type="text/javascript">
/* SLIDESHOW AT HOMEPAGE */
function slideSwitch() {
var $active = $('#slideshow IMG.active');
if ( $active.length == 0 ) $active = $('#slideshow IMG:last');
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
$active.addClass('last-active');
$next.css({opacity: 0.0})
.addClass('active')
.animate({opacity: 1.0}, 1000, function() {
$active.removeClass('active last-active');
});
}
$(function() {
setInterval( "slideSwitch()", 5000 );
});
</script>
<script type="text/javascript">
/* Function to show/hide the side menu for all images */
function showDIV(e)
{
var notEmpty = true;
var count = 0;
while(document.getElementById('subCat'+count) != null)
{
document.getElementById('subCat'+count).style.display = 'none';
count++;
}
document.getElementById(e).style.display = 'block';
}
/* MENU INTERACTION */
function showContent(cmd, id)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("contentMain").innerHTML=xmlhttp.responseText;
document.getElementById("controller").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getMain.php?cmd="+cmd+"&id="+id,true);
xmlhttp.send();
}
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-21909616-1']);
_gaq.push(['_setDomainName', '.karimtabar.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO 8859-1" />
<link rel="stylesheet" type"text/css" href="css/stylesheet.css" />
<link rel="shortcut icon" href="logo/icon.jpg">
<title>KARIM V TABAR PHOTOGRAPHY</title>
<meta name="description" content="Karim V Tabar: photographer, new media, film, design." />
</head>
<body style="width:100%;">
<div id="wholewrapper" >
<!-- HEADER // TOP PORTION OF SITE -->
<div id="logoheader">
<h5 class="logo">
KARIM VICTOR TABAR
</h5>
</div>
<div class="wrapper">
<div class="navcontainer">
<?php
$count = 0;
foreach (new DirectoryIterator('images/menuImages') as $fileInfo)
{
if($fileInfo->isDot()) continue;
echo "<h2 class='acc_trigger' onclick=\"showDIV('subCat".$count."'); showContent(1, '".$fileInfo->getFilename() ."');\"><a href='#'>".$fileInfo->getFilename() ."</a></h2><div class='acc_container' id='container".$count."'><div class='block' name='subCats' id='subCat".$count."'><ul>";
foreach (new DirectoryIterator('images/menuImages/'.$fileInfo) as $fileInfo2)
{
if($fileInfo2->isDot() || $fileInfo2 == "thumbnails") continue;
echo "<li>".$fileInfo2->getFilename() . "</li>";
}
echo "</ul></div></div>";$count++;
}
?>
<div id="navigationlinks">
<ul>
<li>BIO</li>
<li>CONTACT</li>
<li>BLOG</li></ul>
</div>
</div>
<!-- Images Thumbnails Categories -->
<div id="contentMain">
<div id="slideshow">
<img src="images/homepage/bb1.jpg" width = "750px" alt="" class="active" />
<img src="images/homepage/et1.jpg" width = "750px" alt="" />
<img src="images/homepage/gaga1.jpg" width = "750px" alt="" />
<img src="images/homepage/gaga2.jpg" width = "750px" alt="" />
<img src="images/homepage/hkartwalk.jpg" width = "750px" alt="" />
<img src="images/homepage/homepagegirl.jpg" width = "750px" alt="" />
<img src="images/homepage/rodeo2.jpg" width = "750px" alt="" />
<img src="images/homepage/rodeo5.jpg" width = "750px" alt="" />
<img src="images/homepage/silverwig_gaga.jpg" width = "750px" alt="" />
<img src="images/homepage/wavy1.jpg" width = "750px" alt="" />
<img src="images/homepage/Wenya.jpg" width = "750px" alt="" />
</div>
</div>
</body>
</html>
And Here is the Php code that generates the new HTML(getMain.php)
<?php
$cmd=$_GET["cmd"];
$id = $_GET["id"];
/* The Thumbnail Display */
if($cmd == 1)
{
echo "<div id='thumbnailcontentplaceholder'>";
echo "<div id='thumbnailcontent'>";
echo "<ul>";
$dir = "images/menuImages/".$id."/thumbnails";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) != false) {
if(is_dir($file)) continue;
echo "<li>";
echo "<a href='#' title='".$file."'><img src='".$dir."/".$file."' alt='' /></a>";
echo "<div id='thumnailtitle'>".substr($file, 0, strpos($file, "."))."</div>";
echo "</li>";
}
closedir($dh);
}
}
echo "</div></div>";
}
if($cmd == 2)
{
$dir = "images/menuImages/".$id;
$count = 1;
$nFiles = countFiles($dir);
echo "<div id='imageplaceholder'> \n";
/* No1 No2 No3 ... */
echo "<div id='controller' class='hidden'>\n";
for($i =1; $i < $nFiles; $i++)
{
echo "<span class='jFlowControl'>No ".$i."</span>\n";
}
echo "</div>";
echo "<div id='slides'>";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) != false) {
if(is_dir($file)) continue;
echo "<div><img src='".$dir."/".$file."'></div>\n";
}
closedir($dh);
}
}
echo "</div>\n";
echo '<div id="prevNext">
<a id="prev_275997_0" class="jFlowPrev" href="#" onfocus="this.blur()">Previous</a>
<span class="slide_slash">/</span>
<a id="next_275997_0" class="jFlowNext" href="#" onfocus="this.blur()">Next image</a> </div>';
echo '<div id="credits2">
BEIJING BLUE<br>
Photographed by: Karim V Tabar<br></div></div>';
}
function countFiles($dir)
{
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
if ($files)
$num_of_files = count($files) - 2; // we substract 2 because . and .. are included
else
die('there is an error');
return $num_of_files;
}
?>
Thanks
Real HTML that used to work was like this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../../js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script src="../../js/jquery.flow.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
//Set default open/close settings
$('.acc_container').hide(); //Hide/close all containers
$('.acc_trigger:first').addClass('active').next().show(); //Add "active" class to first trigger, then show/open the immediate next container$(document).ready(function(){
//On Click
$('.acc_trigger').click(function(){
('#open').click()
});
});
</script>
<script type="text/javascript">
$(function() {
$("div#controller").jFlow({
slides: "#slides",
width: "785px",
height: "480px"
});
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-21909616-1']);
_gaq.push(['_setDomainName', '.karimtabar.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type"text/css" href="../../css/stylesheet.css">
<link rel="shortcut icon" href="../../logo/icon.jpg">
<title>KARIM V TABAR PHOTOGRAPHY</title>
<meta name="description" content="Karim V Tabar: photographer, new media, film, design." />
</head>
<body style="width:100%;">
<div id="wholewrapper">
<!-- HEADER // TOP PORTION OF SITE -->
<div id="logoheader">
<h5 class="logo">
KARIM VICTOR TABAR
</h5>
</div>
<div class="wrapper">
<div class="navcontainer">
<h2 class="acc_trigger">EDITORIAL</h2>
<div class="acc_container">
<div class="block"> <ul> <li>BEIJING BLUE</li>
<li>GAGA</li>
<li>DOUBLE TROUBLE</li>
<li>EXTRATERRESTRIAL DREAMS</li>
<li>LIFE RUSH</li>
<li>RODEO GLAM</li>
<li>WANDERLUST</li>
<li>RUN AWAY ANGEL</li>
<li>RUSSIAN STANDARD</li>
<li>HOLLYWOOD HILLS</li></ul>
</div>
</div> <h2 class="acc_trigger">TRAVEL</h2>
<div class="acc_container">
<div class="block">
<ul>
<li>HONG KONG</li> </li>
<li>DUBAI, UAE</li>
<li>KYOTO, JAPAN</li>
<li>MIAMI, USA</li>
<li>L.A., USA</li></ul>
</div>
</div>
<h2 class="acc_trigger">ART</h2>
<div class="acc_container">
<div class="block">
<ul> <li>MIRROR ANGEL</li>
<li>ROUGE</li>
<li>VIOLET</li>
<li>NOIRE</li></ul>
</div>
</div> <h2 class="acc_trigger">VIDEO</h2>
<div class="acc_container">
<div class="block">
<ul>
<li>ZIGMAT - BETWEEN BULLETS VIDEO</li><li>ZIGMAT - BEHIND THE SCNES</li></ul>
</div>
</div>
<h2 class="acc_trigger">EXHIBITIONS</h2>
<div class="acc_container">
<div class="block">
<ul>
<li>2009 RESIDENT, MONTRÉAL, CANADA</li><li>2011 ART WALK, HONG KONG, CHINA</li>
</ul>
</div>
</div><!-- <h2 class="acc_trigger">PRESS</h2>
<div class="acc_container">
<div class="block">
<ul>
<li>NME</li>
<li>LIVE FAST MAG</li>
<li>GURU</li></ul>
</div>
</div>
--><div id="navigationlinks">
<ul>
<li>BIO</li>
<li>CONTACT</li>
<li>BLOG</li></ul>
</div> <!-- <div id="buyherelogo">
<img src="../../store/buyhere.png" width="150" border="0">
</div>
--></div>
<!--IMAGE // RIGHT PORTION -->
<div id="imageplaceholder">
<div id="controller" class="hidden">
<span class="jFlowControl">No 1</span>
<span class="jFlowControl">No 2</span>
<span class="jFlowControl">No 3</span>
<span class="jFlowControl">No 4</span>
<span class="jFlowControl">No 5</span>
<span class="jFlowControl">No 6</span>
<span class="jFlowControl">No 7</span>
</div>
<div id="slides">
<div><img src="../../images/fashion/beijingblue/bb1.jpg" width="785" height="480"></div>
<div><img src="../../images/fashion/beijingblue/bb2.jpg" width="785" height="480"></div>
<div><img src="../../images/fashion/beijingblue/bb3.jpg" width="785" height="480"></div>
<div><img src="../../images/fashion/beijingblue/bb4.jpg" width="785" height="480"></div>
<div><img src="../../images/fashion/beijingblue/bb5.jpg" width="785" height="480"></div>
<div><img src="../../images/fashion/beijingblue/bb6.jpg" width="785" height="480"></div>
<div><img src="../../images/fashion/beijingblue/bb7.jpg" width="785" height="480"></div>
</div>
<div id="prevNext">
<a id="prev_275997_0" class="jFlowPrev" href="#" onfocus="this.blur()">Previous</a>
<span class="slide_slash">/</span>
<a id="next_275997_0" class="jFlowNext" href="#" onfocus="this.blur()">Next image</a>
</div>
<div id="credits2">
BEIJING BLUE<br>
Photographed by: Karim V Tabar<br>
</div>
</div>
</div>
</div>
</body>
</html>
When you bind events, or call jQuery functions, the element needs to exist in the DOM for jQuery to find it.
Because you are populating your page after the script has executed, there's no element's to be selected (despite placing the selection in a document.ready callback.
If you did a console.log on $('div#controller') you'd see an empty jQuery object.
If you, instead, used the complete callback to register your jsFlow call, you should see things working as expected.
Is there a reason you're not using jQuery's normalized ajax functions?
You use <div id="contentMain"> in the code, but you call it on div#controller? Anyways, it wouldn't work even if you specified the correct selector, because as zzzzBov answered, when the page loads, your div is empty. You have to recall the jFlow function after you update the content:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("contentMain").innerHTML=xmlhttp.responseText;
$("div#contentMain").jFlow({
slides: "#slides",
width: "785px",
height: "480px"
});
}