set view parameters from another action - php

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.

Related

PHP scroll ajax is not working on mobile but working on localhost or server

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>

Search filter bootstrap card didn't show the specific image

When I'm searching the specific name of the image. The rest of the name of the row still showing, but I just want to view only the data from the search. See image below
Display: Select all the data from the database.
<?php$checkQuery = "SELECT `h_business_logo`,`h_business_name`,`h_business_desc` FROM user_bsns WHERE h_isActive = 1 ORDER BY h_business_name DESC";
$checkResult = mysqli_query($db->conn, "$checkQuery")
?>
Card: This card has an animation
<div class="card-body col-lg-12" >
<div class="card-body col-lg-12">
<input class="form-control" id="myInput" type="text" placeholder="Search.." style="float:left; width:25%;">
<button class="btn" style="margin-left: 5px;background-color: #e72329;color: white;"> Search </button>
</div>
<?php
if(mysqli_num_rows($checkResult) > 0):{
}
while($row = mysqli_fetch_array($checkResult)){
?>
<div class="panel" id="myDIV">
<div class="holder flipH" >
<div class="card shadow-none">
<div class="col-sm-0 column <?=$row['h_business_name'];?>" >
<div class="front"style="float:left; >
<img src="<?=$row['h_business_logo']; ?> "
style="height:150px; width:155px; border-radius: 50%; ">
</div>
</div>
<span style= "text-align:center;">
<h5><?=$row['h_business_name'];?></h5>
</span>
<span style="text-align:center;">
<p><?=$row['h_business_desc'];?></p>
</span>
</div>
</div>
</div>
<?php
}
endif;
?>
</div>
<!-- /.card-body -->
</div>
And this one is the function of the search filter.
<script>
$(document).ready(function(){
$(".btn").on("click", function() {
var value = $("#myInput").val();
lastval = "col-sm-5 column "+value;
x = document.getElementsByClassName("column");
$("#myDIV div").filter(function() {
for (i = 0; i < x.length; i++) {
element = x[i];
if (element.className.indexOf(value) == -1){
element.classList.add("nonshow");
element.classList.remove("show");
}
else {
element.classList.add("show");
element.classList.remove("nonshow");
}
}
});
});
});
</script>
Please help me to improve the codes.
Update: I solved my problem using this script(jquery)
update: I used this script in order to search automatically.
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDiv ").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
});
});
});

How to fix code PHP DOM HTML Parse - Loop

I started to play building a PHP HTML Parser,
and I have some trouble:
The HTML code is as follows:
<div class="list">
<div class="b">
<div class="c">
<a href="http://link.com">
<div class="d">Category</div>
<div class="e">
<img src="https://link.com/img.png">
</div>
<h1>TITLE</h1>
<div class="f">paragraph 1</div>
<div class="g">paragraph 2</div>
<div class="h">
<div class="i">
<div class="j">Quot</div>
</div>
</div>
</a>
</div>
</div>
<div class="b">
<div class="c">
<a href="http://link2.com">
<div class="d">Category2</div>
<div class="e">
<img src="https://link2.com/img.png">
</div>
<h1>TITLE 2</h1>
<div class="f">paragraph 12</div>
<div class="g">paragraph 22</div>
<div class="h">
<div class="i">
<div class="j">Quot 2</div>
</div>
</div>
</a>
</div>
</div>
My PHP Code:
$classname = "list";
$xPath = new DomXPath($dom);
$find = $xPath->query("//*
[contains(#class, '$classname')]");
$get = $find->item(0);
$link = $get->getElementsByTagName('a');
$data = array();
foreach ($link as $val)
{ $data[] = array(
'link' => $link->item($no)
->getAttribute('href'),
);
$no++;
}
I want the results like this:
-http://link.com
-category
-http://link.com/img.png
-paragraph 1
-paragraph 2
-quot
-http://link2.com
-category2
-http://link2.com/img.png
-paragraph 12
-paragraph 22
-quot2
Here is how you could do it using jQuery and Mustache js a templating tool.
https://jsfiddle.net/mcroteau/zyouxfq4/
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript" src="Mustache.js"></script>
<script type="text/javascript">
var row = `
<div class="content-row">
<div class="link">
{{link}}
</div>
<h1>{{category}}</h1>
<img src="{{image}}" style="border:solid 1px #ddd; height:20px; width:20px;"/><br/>
<p>{{paragraphOne}}</p>
<p>{{paragraphTwo}}</p>
<p>{{quote}}</p>
</div>
<hr/>`;
$(document).ready(function(){
var $mainContentDiv = $(".list")
var $mainList = $(".b");
$mainList.each(function(){
var data = {}
var content = $(this).find(".c")
var $content = $(content)
var link = getLink($content)
var category = getCategory($content)
var image = getImage($content)
var paragraphOne = getParagraph($content, 'f')
var paragraphTwo = getParagraph($content, 'g')
var quote = getQuote($content)
data["link"] = link
data["category"] = category
data["image"] = image
data["paragraphOne"] = paragraphOne
data["paragraphTwo"] = paragraphTwo
data["quote"] = quote
var html = Mustache.to_html(row, data);
$('#links-container').append(html);
})
function getQuote($content){
return $content.find(".j").html()
}
function getParagraph($content, className){
return $content.find("." + className).html()
}
function getImage($content){
return $content.find("e").find("img").attr("src")
}
function getCategory($content){
var category = $content.find(".d")
return $(category).html()
}
function getLink($content){
return $content.find("a").attr("href")
}
$mainContentDiv.remove()
})
</script>
Is this something like you wanted to achieve?

div expand and collapse is not working in my php code

In my php page i have these following code:-
<?php
include ('dbConnect/dbConnect.php');
$query = "Select * from RitualType";
$queryResult = mysqli_query($dbcon, $query);
?>
<!-- <div class="panel-grid-cell" id="pgc-110-6-1" >--><br/>
<div class="row-fluid" style="">
<div class="col-md-4" id="" style="position: fixed; left: 50pt; width:254px;height:50px; top: 87px; z-index: 99999999;" >
<div class="textwidget" ><?php $i = 0;
while ($row = mysqli_fetch_array($queryResult)) {
?><div id="SpanHoma">
<span class="" style="color: red;font-size: 14px;"><strong><?php echo $row['Name'] ?></strong></span>
<div class="textwidget" id="RitualsGroup" style="display:none;">
<?php
$query1 = "Select * from Rituals where RitualTypeId=" . $row['Id'];
$queryResult1 = mysqli_query($dbcon, $query1);
?>
<?php while ($row1 = mysqli_fetch_array($queryResult1)) { ?>
<div class="Homas" > <?php echo "<a style='color: #000000;' href='#" . $row1['Id'] . "'>" ?>
<i class="fa fa-hand-o-right"></i> <span class="what-we-offer" style="color: #000000;">
<?php echo $row1['Name'] ?> </span><?php echo '</a>'; ?><br />
</div><?php $i++;
} ?>
</div></div><?php } ?>
</div>
</div>
</div>
Where RitualType is Heading and Rituals are the contents.
I need to make the div expand and collapsible. Right Now the page is like this
A
B
C
D
E
When i click A then the contents of A is getting displayed like
A
a
b
c
B
C
D
E
But when i click B the div is not getting expanded. It only Works for A. I want the particular div to open when i click the Main Heading.
Javascript Code to toggleis shown below
$(function () {
$("#SpanHoma").on("click", function () {
$("#RitualsGroup").toggle();
});
$('.RitualsGroup').hide();
});
You need to try like this (convert id to class in html and change javascript code like below):-
$(function () {
$(".SpanHoma").on("click", function () {
$(this).find(".RitualsGroup").toggle(); // this will check which one is clicked currently
});
});
$(function () {
$(".SpanHoma").on("click", function () {
$(this).find(".RitualsGroup").toggle(); // this will check which one is clicked currently
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class= "SpanHoma">
<span>A</span>
<div class= "RitualsGroup" style = "display:none;">
<li>c</li>
<li>d</li>
<li>e</li>
</div>
</div>
<div class= "SpanHoma">
<span>B</span>
<div class= "RitualsGroup" style = "display:none;">
<li>f</li>
<li>g</li>
<li>h</li>
</div>
</div>
Its because of you are giving same id for multiple div. try this:
change this:
<div id="SpanHoma">
to
<div class="SpanHoma">
and
<div class="textwidget" id="RitualsGroup" style="display:none;">
to
<div class="textwidget RitualsGroup" style="display:none;">
in jquery:
$(function () {
$(".SpanHoma").on("click", function () {
$(this).find(".RitualsGroup").toggle();
});
});

Angular JS posting image and hidden field data to php

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.

Categories