The column I am trying to sort looks like this;
When you look at the image above you see that sort does not follow the right order. Jan 24
should come before Jan 28.
Here's my client-side code :
$(function () {
$("#list").jqGrid({
url:"grid_accessLog.php",
datatype: "json",
mtype: "GET",
colNames:["ID","Ip Address","User Info","Time","Page","Referrer","Search","User Agent","Notes"],
colModel: [
{ name: "id",index:"id", width: 55,search:true},
{ name: "ip_address",index:"ip_address",search:true, width: 90 },
{ name: "user_info",index:"user_info",search:true, width: 100},
{ name: "time",index:"time",search:true,sorttype:"date",width: 90},
{ name: "page",index:"page",search:true, width: 120},
{ name: "referrer",index:"referrer",search:true, width: 90 },
{ name: "search",index:"search",search:true, width: 90 },
{ name: "user_agent",index:"user_agent",search:true, width: 120 },
{ name: "notes",index:"notes",search:true, width: 120 }
],
pager: "#pager",
rowNum: 30,
rowList: [10,20,30],
autowidth:true,
sortname: "id",
sortorder: "desc",
// loadonce: true,
viewrecords: true,
autoencode: true,
caption: "Access Log",
height: 'auto'
}).navGrid("#pager", {search:true, edit:false,add:false,del:false,searchtext:"Search",refreshtext:"Refresh"});
});//end ready
Here's my server-side code;
//Get the requested page
$page = $_GET['page'];
//Get how many rows we want to have into the grid
$limit = $_GET['rows'];
// get index row - i.e. user click to sort. At first time sortname parameter -
// after that the index from colModel
$sidx = $_GET['sidx'];
// sorting order - at first time sortorder
$sord = $_GET['sord'];
// if we not pass at first time index use the first column for the index or what you want
if(!$sidx) $sidx =1;
//array to translate the search type
$ops = array(
'eq'=>'=', //equal
'ne'=>'<>',//not equal
'lt'=>'<', //less than
'le'=>'<=',//less than or equal
'gt'=>'>', //greater than
'ge'=>'>=',//greater than or equal
'bw'=>'LIKE', //begins with
'bn'=>'NOT LIKE', //doesn't begin with
'in'=>'LIKE', //is in
'ni'=>'NOT LIKE', //is not in
'ew'=>'LIKE', //ends with
'en'=>'NOT LIKE', //doesn't end with
'cn'=>'LIKE', // contains
'nc'=>'NOT LIKE' //doesn't contain
);
function getWhereClause($col, $oper, $val){
global $ops;
if($oper == 'bw' || $oper == 'bn') $val .= '%';
if($oper == 'ew' || $oper == 'en' ) $val = '%'.$val;
if($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') $val = '%'.$val.'%';
return " WHERE $col {$ops[$oper]} '$val' ";
}
$where = ""; //if there is no search request sent by jqgrid, $where should be empty
$searchField = isset($_GET['searchField']) ? $_GET['searchField'] : false;
$searchOper = isset($_GET['searchOper']) ? $_GET['searchOper']: false;
$searchString = isset($_GET['searchString']) ? $_GET['searchString'] : false;
if ($_GET['_search'] == 'true') {
$where = getWhereClause($searchField,$searchOper,$searchString);
}
mysql_query("SET NAMES 'utf8'");
// calculate the number of rows for the query. We need this for paging the result
$result = mysql_query("SELECT COUNT(*) AS count FROM renal_accessLog");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
// calculate the total pages for the query
if( $count > 0 && $limit > 0) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
// if for some reasons the requested page is greater than the total
// set the requested page to total page
if ($page > $total_pages) $page=$total_pages;
// calculate the starting position of the rows
$start = $limit*$page - $limit;
// if for some reasons start position is negative set it to 0
// typical case is that the user type 0 for the requested page
if($start <0) $start = 0;
// the actual query for the grid data
$SQL = "SELECT * FROM renal_accessLog ".$where." ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());
$responce = new stdClass();
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$responce->rows[$i]['id']=$row['id'];
$responce->rows[$i]['cell']=array($row['id'],$row['ip_address'],$row['user_info'],$row['time'],$row['page'],$row['referrer'],$row['search'],$row['user_agent'],$row['notes'] );
$i++;
}
echo json_encode($responce);
I have the same problem on sorting an address column on another grid. I hope that if I can get this one fixed, I can apply the same logic to the other grid. Thanks for you input!
Ok so what I did was since time does not sort in the right order, and time and id are corollaries, I added this piece of checking to my query.
//checking if time is the sort column clicked so that we can default sidx to id..
if($sidx =='time'){
$SQL = "SELECT * FROM renal_accessLog ".$where." ORDER BY id $sord LIMIT $start, $limit";
}else{
$SQL = "SELECT * FROM renal_accessLog ".$where." ORDER BY $sidx $sord LIMIT $start , $limit";
}
$result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());
Related
i have the following code on my controller:
/**
*
* #Route("/{discountLevelItemId}/manage-product/update", name="discountlevel_manage_product_update", defaults={"_format"="json"} )
* #Method("POST")
*/
public function manageProductUpdateAction($discountLevelItemId, Request $request)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('CIInventoryBundle:DiscountLevelItem')->find($discountLevelItemId);
$form = $this->createForm(new DiscountLevelItemCollectionType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
//remove items without discount type
foreach ($entity->getDiscountLevelItemProducts() as $item) {
if (!$item->getDiscountType()) {
$entity->getDiscountLevelItemProducts()->removeElement($item);
$em->remove($item);
}
}
$em->persist($entity);
$em->flush();
$responseData = array(
'status' => 'success',
'message' => 'Supplier product discounts successfully saved.'
);
} else {
$responseData = array(
'status' => 'error',
'form' => $this->renderView('CIInventoryBundle:DiscountLevel:manageProducts.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
))
);
}
return new Response(json_encode($responseData), 200, array('Content-Type'=>'application/json'));
}
This action is called via ajax. Before calling this controller i filtered some data out like so:
initForm: function() {
//submit form function
var options = {
delegation: true,
dataType: "json",
beforeSubmit: function(arr, $form, options) {
//holds objects every four looping
var tempArray = new Array();
//holds changed objects that will only be submitted in the server.
var changedArray = new Array();
var found = false;
var idx = 1;
//get the token then remove from arr.
changedArray.push(arr.splice(arr.length-1,1)[0]);
for (var j = arr.length-1; j >= 0; j--) {
var obj = arr[j];
if ( viewCtrl.dliProductsChanged.indexOf(obj.value) != -1 ) {
found = true;
}
tempArray.push(arr[j]);
if(idx % 4 == 0) {
if (found == true) {
for(var i = 0; i < tempArray.length; i++){
changedArray.push(tempArray[i]);
}
found = false;
}
tempArray.length = 0;
}
idx++;
}
arr.length = 0;
for(var i = 0; i < changedArray.length; i++){
arr.push(changedArray[i]);
}
viewCtrl.dliProductsChanged.length = 0;
$form.find( ".submit-button" ).button( "loading" );
$form.find( ".discount-value, .trucking" ).addClass( "uneditable-input" );
$form.find( ".discount-type" ).attr( "readonly", true );
},
success: function(responseText, statusText, xhr, $form) {
if ( responseText.status == "success" ) {
viewCtrl.modal.modal( "hide" );
$.growl.notice({ title: "<strong>Saved</strong>", message: responseText.message, size: "large", duration: 5000, location: "br" });
viewCtrl.dliProductsChanged.length = 0;
} else {
viewCtrl.modal.find( ".modal-content" ).html( responseText.form );
}
$form.find( ".submit-button" ).button( "reset" );
}
};
$( "#manage-products-form" ).ajaxForm( options );
},
My question is, how can i repopulate the form with data i filtered out when the form gets invalid? The first thing came out of my mind is modifying the request object and then rebinding it again but i dont know how to implement that...
Any insights?
PS: I user JQUERY Form Plugin on form submission.
Thanks!
I am having trouble passing SQL data from my controller to my view. I have verified the information shows up from my model. I don't know JSON very well but I'm trying to learn. My goal is to populate a chart with two fields that are just numbers into this highcharts javascript. Please help, thank you!
Controller
function dashboard() {
// Tickets in Queue
$query = $this->mhedash_model->maint_pending_tickets();
$result3 = $query->result_array();
$this->table->set_heading('Work Number', 'Vehicle Number','Submit Date','Submit Time');
$data['table']['Vehicle in Queue'] = $this->table->generate_table($result3);
// Active Tickets
$query = $this->mhedash_model->select_active();
$result = $query->result_array();
$this->table->set_heading('Service Number','Start Date','Mechanic','Vehicle Number','Description','Type');
$data['table']['Vehicles Actively Being Worked On'] = $this->table->generate_table($result);
// Tickets Waiting On Parts
$query = $this->mhedash_model->select_pending_parts();
$result2 = $query->result_array();
$this->table->set_heading('Service Number','Start Date','Mechanic','Vehicle Number','Description','Type');
$data['table']['Waiting For Parts'] = $this->table->generate_table($result2);
//Graph - Availble Highreaches
$query = $this->mhedash_model->graph_available_hr();
$result4 = $query->result_array();
$data['row'][''] = $this->table->generate_table($result4);
$query = $this->mhedash_model->graph_available_dt();
$result5 = $query->result_array();
$data['row'][''] = $this->table->generate_table($result5);
$series_data[] = array('name' => 'available', 'data' => (int)$result4);
$series_data[] = array('name' => 'not_available', 'data' => (int)$result5);
$this->view_data['series_data'] = json_encode($series_data, JSON_NUMERIC_CHECK);
// Load view
$data['page_title'] = 'MHE Dashboard';
$data['main_content'] = 'mhe/mhe_dashboard_view';
$data['array'] = $result;
$data['array2'] = $result2;
$data['array3'] = $result3;
print json_encode($series_data);
//echo json_encode($series_data, JSON_NUMERIC_CHECK);
return $this->load->view('includes/template',$data);
}
View that has the highcharts javascript
var chart;
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
xAxis: {
categories: ['one', 'two']
},
plotOptions: {
series: {
allowPointSelect: true
}
},
series: [{
data: [<?php echo join($series_data, ',') ?>]
}]
});
// the button action
$('#button').click(function () {
var chart = $('#container').highcharts(),
selectedPoints = chart.getSelectedPoints();
if (chart.lbl) {
chart.lbl.destroy();
}
chart.lbl = chart.renderer.label('You selected ' + selectedPoints.length + ' points', 100, 60)
.attr({
padding: 10,
r: 5,
fill: Highcharts.getOptions().colors[1],
zIndex: 5
})
.css({
color: 'white'
})
.add();
});
});
</script>
Also, this is what prints when I print son_encode for my $series_data
[{"name":"available","data":1},{"name":"not_available","data":1}]
I have page of articles with more than 5 results. 5 results are displayed per page. Pagination shows up. When I go to different pages however, every page has the same 5 results.
My getItems():
function getItems()
{
$params = $this->getState()->get('params');
$limit = $this->getState('list.limit');
// 5
if ($this->_articles === null && $category = $this->getCategory()) {
$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
$model->setState('params', JFactory::getApplication()->getParams());
$model->setState('filter.category_id', $category->id);
$model->setState('filter.published', $this->getState('filter.published'));
$model->setState('filter.access', $this->getState('filter.access'));
$model->setState('filter.language', $this->getState('filter.language'));
$model->setState('list.ordering', $this->_buildContentOrderBy());
$model->setState('list.start', $this->getState('list.start'));
$model->setState('list.limit', $limit);
$model->setState('list.direction', $this->getState('list.direction'));
$model->setState('list.filter', $this->getState('list.filter'));
// filter.subcategories indicates whether to include articles from subcategories in the list or blog
$model->setState('filter.subcategories', $this->getState('filter.subcategories'));
$model->setState('filter.max_category_levels', $this->setState('filter.max_category_levels'));
$model->setState('list.links', $this->getState('list.links'));
if ($limit >= 0) {
$this->_articles = $model->getItems();
if ($this->_articles === false) {
$this->setError($model->getError());
}
}
else {
$this->_articles=array();
}
$this->_pagination = $model->getPagination();
}
$filterResult = null;
return $this->_articles;
}
My populate state:
protected function populateState($ordering = null, $direction = null)
{
// Initiliase variables.
$app = JFactory::getApplication('site');
$pk = JRequest::getInt('id');
$this->setState('category.id', $pk);
// Load the parameters. Merge Global and Menu Item params into new object
$params = $app->getParams();
$menuParams = new JRegistry;
if ($menu = $app->getMenu()->getActive()) {
$menuParams->loadString($menu->params);
}
$mergedParams = clone $menuParams;
$mergedParams->merge($params);
$this->setState('params', $mergedParams);
$user = JFactory::getUser();
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
$groups = implode(',', $user->getAuthorisedViewLevels());
if ((!$user->authorise('core.edit.state', 'com_content')) && (!$user->authorise('core.edit', 'com_content'))){
// limit to published for people who can't edit or edit.state.
$this->setState('filter.published', 1);
/**
* Custom Author Filter
*/
if (JRequest::getVar('author')) {
$this->setState('filter.created_by', $this->getUserId(JRequest::getVar('author')));
}
// Filter by start and end dates.
$nullDate = $db->Quote($db->getNullDate());
$nowDate = $db->Quote(JFactory::getDate()->toMySQL());
$query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')');
$query->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
/**
* Custom Author Filter
*/
if (JRequest::getVar('author')) {
$query->where('(a.created_by = "' . $this->getUserId(JRequest::getVar('author')) . '")');
}
}
// process show_noauth parameter
if (!$params->get('show_noauth')) {
$this->setState('filter.access', true);
}
else {
$this->setState('filter.access', false);
}
// Optional filter text
$this->setState('list.filter', JRequest::getString('filter-search'));
// filter.order
$itemid = JRequest::getInt('id', 0) . ':' . JRequest::getInt('Itemid', 0);
$orderCol = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.filter_order', 'filter_order', '', 'string');
if (!in_array($orderCol, $this->filter_fields)) {
$orderCol = 'a.ordering';
}
$this->setState('list.ordering', $orderCol);
$listOrder = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.filter_order_Dir',
'filter_order_Dir', '', 'cmd');
if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', ''))) {
$listOrder = 'ASC';
}
$this->setState('list.direction', $listOrder);
//$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));
// set limit for query. If list, use parameter. If blog, add blog parameters for limit.
if ((JRequest::getCmd('layout') == 'blog') || $params->get('layout_type') == 'blog') {
$limit = $params->get('num_leading_articles') + $params->get('num_intro_articles') + $params->get('num_links');
$this->setState('list.links', $params->get('num_links'));
}
else {
$limit = $app->getUserStateFromRequest('com_content.category.list.' . $itemid . '.limit', 'limit', $params->get('display_num'));
}
$this->setState('list.limit', $limit);
// set the depth of the category query based on parameter
$showSubcategories = $params->get('show_subcategory_content', '0');
if ($showSubcategories) {
$this->setState('filter.max_category_levels', $params->get('show_subcategory_content', '1'));
$this->setState('filter.subcategories', true);
}
$this->setState('filter.language',$app->getLanguageFilter());
$this->setState('layout', JRequest::getCmd('layout'));
}
My display function de view.html.php
function display($tpl = null)
{
$app = JFactory::getApplication();
$user = JFactory::getUser();
// Get some data from the models
$state = $this->get('State');
$params = $state->params;
$items = $this->get('Items');
$contactId = JRequest::getVar('author');
if($contactId){
$this->setUserId($contactId);
$this->setContactName($this->userId);
}
$category = $this->get('Category');
$children = $this->get('Children');
$parent = $this->get('Parent');
$pagination = $this->get('Pagination');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
JError::raiseError(500, implode("\n", $errors));
return false;
}
if ($category == false) {
return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
}
if ($parent == false) {
return JError::raiseError(404, JText::_('JGLOBAL_CATEGORY_NOT_FOUND'));
}
// Setup the category parameters.
$cparams = $category->getParams();
$category->params = clone($params);
$category->params->merge($cparams);
// Check whether category access level allows access.
$user = JFactory::getUser();
$groups = $user->getAuthorisedViewLevels();
if (!in_array($category->access, $groups)) {
return JError::raiseError(403, JText::_("JERROR_ALERTNOAUTHOR"));
}
// PREPARE THE DATA
// Get the metrics for the structural page layout.
$numLeading = $params->def('num_leading_articles', 1);
$numIntro = $params->def('num_intro_articles', 4);
$numLinks = $params->def('num_links', 4);
// Compute the article slugs and prepare introtext (runs content plugins).
for ($i = 0, $n = count($items); $i < $n; $i++)
{
$item = &$items[$i];
$item->slug = $item->alias ? ($item->id . ':' . $item->alias) : $item->id;
// No link for ROOT category
if ($item->parent_alias == 'root') {
$item->parent_slug = null;
}
$item->event = new stdClass();
$dispatcher = JDispatcher::getInstance();
// Ignore content plugins on links.
if ($i < $numLeading + $numIntro) {
$item->introtext = JHtml::_('content.prepare', $item->introtext);
$results = $dispatcher->trigger('onContentAfterTitle', array('com_content.article', &$item, &$item->params, 0));
$item->event->afterDisplayTitle = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentBeforeDisplay', array('com_content.article', &$item, &$item->params, 0));
$item->event->beforeDisplayContent = trim(implode("\n", $results));
$results = $dispatcher->trigger('onContentAfterDisplay', array('com_content.article', &$item, &$item->params, 0));
$item->event->afterDisplayContent = trim(implode("\n", $results));
}
}
// Check for layout override only if this is not the active menu item
// If it is the active menu item, then the view and category id will match
$active = $app->getMenu()->getActive();
if ((!$active) || ((strpos($active->link, 'view=category') === false) || (strpos($active->link, '&id=' . (string) $category->id) === false))) {
// Get the layout from the merged category params
if ($layout = $category->params->get('category_layout')) {
$this->setLayout($layout);
}
}
// At this point, we are in a menu item, so we don't override the layout
elseif (isset($active->query['layout'])) {
// We need to set the layout from the query in case this is an alternative menu item (with an alternative layout)
$this->setLayout($active->query['layout']);
}
// For blog layouts, preprocess the breakdown of leading, intro and linked articles.
// This makes it much easier for the designer to just interrogate the arrays.
if (($params->get('layout_type') == 'blog') || ($this->getLayout() == 'blog')) {
$max = count($items);
// The first group is the leading articles.
$limit = $numLeading;
for ($i = 0; $i < $limit && $i < $max; $i++) {
$this->lead_items[$i] = &$items[$i];
}
// The second group is the intro articles.
$limit = $numLeading + $numIntro;
// Order articles across, then down (or single column mode)
for ($i = $numLeading; $i < $limit && $i < $max; $i++) {
$this->intro_items[$i] = &$items[$i];
}
$this->columns = max(1, $params->def('num_columns', 1));
$order = $params->def('multi_column_order', 1);
if ($order == 0 && $this->columns > 1) {
// call order down helper
$this->intro_items = ContentHelperQuery::orderDownColumns($this->intro_items, $this->columns);
}
$limit = $numLeading + $numIntro + $numLinks;
// The remainder are the links.
for ($i = $numLeading + $numIntro; $i < $limit && $i < $max;$i++)
{
$this->link_items[$i] = &$items[$i];
}
}
$children = array($category->id => $children);
//Escape strings for HTML output
$this->pageclass_sfx = htmlspecialchars($params->get('pageclass_sfx'));
$this->assign('maxLevel', $params->get('maxLevel', -1));
$this->assignRef('state', $state);
$this->assignRef('items', $items);
$this->assignRef('category', $category);
$this->assignRef('children', $children);
$this->assignRef('params', $params);
$this->assignRef('parent', $parent);
$this->assignRef('pagination', $pagination);
$this->assignRef('user', $user);
$this->_prepareDocument();
parent::display($tpl);
}
If i print the contents of $pagination in the view.html.php here:
$this->_prepareDocument();
echo '<pre>'; print_r($pagination); exit();
parent::display($tpl);
I get the following results:
In my template file I echo the pagination:
<?php echo $this->pagination->getPagesLinks(); ?>
By the way, clicking on 'next' does change the url into ...?start=5.
This line in populateState is commented out
$this->setState('list.start', JRequest::getVar('limitstart', 0, '', 'int'));
Uncomment it change it tot get the "start" parameter:
$this->setState('list.start', JRequest::getVar('start', 0, '', 'int'));
My Cart is looking like this with popup window:
I am updating multiple configurable items in cart with custom options at a time by AJAX Call.
But I am not able to get all items data back to AJAX response.
I am getting just 1st itemPrice and rowTotal. For remaining items itemPrice and rowTotal are set to 0.
Code:
public function updateItemOptionsAction()
{
$cartData = $this->getRequest()->getParam('cart');
Mage::log($cartData);
if (is_array($cartData)) {
$result = array();
$result['data'] = array();
foreach ($cartData as $index => $data) {
$cart = $this->_getCart();
$params = $data;
$id = (int)$data['id'];
if (!isset($params['options'])) {
$params['options'] = array();
}
$result['data'][$index] = array();
$oldQty = null;
$kitType = $params['efk_kType'];
$params['super_attribute'] = array($data['sAttr']=>$kitType);
unset($params['sAttr']);
$stock = null;
try {
if (isset($params['qty'])) {
$product = Mage::getModel("catalog/product")->load($params['product']);
$childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product);
foreach($childProducts as $cProd){
if($cProd->getKitType() == $kitType){
$stock = intval(Mage::getModel('cataloginventory/stock_item')->loadByProduct($cProd)->getQty());
}
}
if(intval($params['qty']) > $stock){
$oldQty = intval($params['qty']);
$params['qty'] = $stock;
$result['data'][$index]['revised'] = true;
}
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$quoteItem = Mage::getSingleton('checkout/cart')->getQuote()->getItemById($id);
if (!$quoteItem) {
Mage::throwException($this->__('Quote item is not found.'));
}
//Its going to infinity loop duwe to Varien Object need to check later
//$item = $cart->updateItem($id, new Varien_Object($params));
$item = Mage::getSingleton('checkout/cart')->updateItem($id, $params);
if (is_string($item)) {
Mage::throwException($item);
}
if ($item->getHasError()) {
Mage::throwException($item->getMessage());
}
Mage::log('hi2');
$related = $params['related_product'];
if (!empty($related)) {
Mage::getSingleton('checkout/cart')->addProductsByIds(explode(',', $related));
}
Mage::getSingleton('checkout/cart')->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
Mage::dispatchEvent('checkout_cart_update_item_complete',
array('item' => $item, 'request' => $this->getRequest(), 'response' => $this->getResponse())
);
$cart->getQuote()->setTotalsCollectedFlag(false);
Mage::getSingleton('checkout/cart')->init();
if (!Mage::getSingleton('checkout/session')->getNoCartRedirect(true)) {
if (!Mage::getSingleton('checkout/cart')->getQuote()->getHasError()) {
Mage::log('hi4');
$result['success'] = true;
if($oldQty > $item->getQty()){
$message = $this->__('%s has been revised due to stock limitations. You may proceed with the order for the revised quantity.', Mage::helper('core')->escapeHtml($item->getProduct()->getName()));
}else{
$message = $this->__('%s was updated in your shopping cart.', Mage::helper('core')->escapeHtml($item->getProduct()->getName()));
}
$result['data'][$index]['message'] = $message;
$result['data'][$index]['itemId'] = $item->getId();
$result['data'][$index]['itemPrice'] = Mage::helper('checkout')->formatPrice($item->getCalculationPrice());
$result['data'][$index]['qty'] = $item->getQty();
$result['data'][$index]['rowTotal'] = Mage::helper('checkout')->formatPrice($item->getRowTotal());
}
}
} catch (Mage_Core_Exception $e) {
$result['success'] = false;
$result['data'][$index]['success'] = 'qty';
$result['data'][$index]['message'] = $e->getMessage();
} catch (Exception $e) {
$result['success'] = false;
$result['data'][$index]['message'] = $e->getMessage();
$result['data'][$index]['secondMessage'] = $this->__('Cannot update the item.');
}
}
$result['data']['grandTotal'] = Mage::helper('checkout')->formatPrice(Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal());
$result['data']['totalItems'] = Mage::getSingleton('checkout/cart')->getSummaryQty();
$totals = Mage::getSingleton('checkout/cart')->getQuote()->getTotals();
$result['data']['subTotal'] = Mage::helper('checkout')->formatPrice($totals['subtotal']->getValue());
if(isset($totals['discount']) && $totals['discount']->getValue()){
$result['data']['discount'] = Mage::helper('checkout')->formatPrice($totals['discount']->getValue());
}else{
$result['data']['discount'] = Mage::helper('checkout')->formatPrice(0);
}
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}
AJAX Response I'm getting
{
"data": {
"1187": {
"success": true,
"message": "THREE PHASE SOLID STATE RELAY WITH ZVS was updated in your shopping cart.",
"itemId": "1191",
"itemPrice": "<span class=\"price\">20b9 3,799</span>",
"qty": 1,
"rowTotal": "<span class=\"price\">20b9 3,799</span>",
"forLoop": "yes"
},
"1189": {
"success": true,
"message": "AUTO INTENSITY CONTROL OF STREET LIGHTS was updated in your shopping cart.",
"itemId": "1193",
"itemPrice": "<span class=\"price\">20b9 0</span>",
"qty": 1,
"rowTotal": "<span class=\"price\">20b9 0</span>",
"forLoop": "yes"
},
"grandTotal": "<span class=\"price\">20b9 8,798</span>",
"totalItems": 2,
"subTotal": "<span class=\"price\">20b9 8,798</span>",
"discount": "<span class=\"price\">20b9 0</span>"
}
}
I am getting itemPrice and rowTotal for 2nd item as 0. Every time I am getting correct values for 1st item only. If i am update 5 items at a time (say for example) then i am getting correct values for 1st item and for remianing items i am getting 0's.
If i refresh cart once i get AJAX response, then it is showing itemPrice and rowTotal updated values correctly for all items.
Note: 20b9 is HEX Code for Indian Rupee symbol
Please point out where i am wrong.
Thanks in advance.
You're working tooooo hard... try updating the items in the controller server side as you sort of are, saving the current quote... and then just have a controller method that loads the current .phtml and returns the html as json for the cart block, and replace the whole cart html block (div) with the new one.
At the end of your controller method
$this->getResponse()->setBody( json_encode(
array("html" =>
Mage::app()->getLayout()->createBlock('checkout/[[whatevertag_is_to_cart_div phtml block]]')->toHtml()
)
);
I am attempting to use a variable in my SELECT statement but I'm running into some very strange problems .code below.
do not work,none data!
Code:
$fid= $_GET['f'];
echo $fid;//prints 3
$SQL = "SELECT threadid, thumb, title, stage, status, startdate ,duedate, forumid FROM thread WHERE forumid = '$fid' ";
work fine!
**Code:**
$SQL = "SELECT threadid, thumb, title, stage, status, startdate ,duedate, forumid FROM thread WHERE forumid ='3' ";
thank you!
grid.php
<?php include ("add/add_config.php");?>
<?php include ("php/jqAutocomplete.php");?>
<?php include ("php/jqCalendar.php");?>
<?php include ("php/jqGrid.php");?>
<?php
ini_set("display_errors","1");
$fid= $_GET['f'];
include ("php/jqGridPdo.php");
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
$conn->query("SET NAMES utf8");
// Create the jqGrid instance
$grid = new jqGridRender($conn);
echo $fid;
$grid->SelectCommand ="SELECT threadid, thumb, title, stage, status, startdate ,duedate FROM thread WHERE forumid='3'";
//$g="SELECT threadid, thumb, title, stage, status, startdate ,duedate, forumid FROM thread WHERE forumid='$fid'";
//echo $g;
// set the ouput format to json
$grid->dataType = 'json';
$grid->table ="thread";
$grid->setPrimaryKeyId("threadid");
$grid->setUrl('grid.php');
$grid->cacheCount = true;
$grid->addCol(array(
"name"=>"actions",
"formatter"=>"actions",
"editable"=>false,
"sortable"=>false,
"resizable"=>false,
"fixed"=>true,
"width"=>60,
"formatoptions"=>array("keys"=>true)
), "first");
$grid->setGridOptions(array(
"caption"=>"cdbdev",
"rownumbers"=>true,
"toppager"=>true,
"rowNum"=>10,
"sortname"=>"threadid",
"hoverrows"=>true,
"rowList"=>array(10,20,50),
"postData"=>array("grid_recs"=>776),
"height"=>"auto",
"width"=>"auto"
));
$grid->addCol(array("name"=>"fileToUpload", "editable"=>true, "edittype"=>"file", "editrules"=>array("edithidden"=>true)));
$upload = <<<UPLOAD
function(formid) {
//These are needed for fileupload plugin
$(formid).attr("method","POST");
$(formid).attr("action","");
$(formid).attr("enctype","multipart/form-data");
$("<br/><button id='buttonUpload'>Upload</button>").insertAfter("#fileToUpload",formid);
// bind a event
$("#buttonUpload",formid).click(function(){
$.ajaxFileUpload({
url:'doajaxfileupload.php',
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json',
success: function (data, status) {
console.log(data);
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else{
$("#fileToUpload").val("");
alert(data.msg);
}
}
},
error: function (data, status, e)
{
alert(e);
}
});
return false;
});
}
UPLOAD;
$grid->setJSCode($upload);
$image = <<<CUSTOM
function formatImage(cellValue, options, rowObject) {
var imageHtml = "<img src='images/" + cellValue + "' originalValue='" + cellValue + "' />";
return imageHtml;
}
function unformatImage(cellValue, options, cellObject) {
return $(cellObject.html()).attr("originalValue");
}
function formatRating(cellValue, options, rowObject) {
var color = (parseInt(cellValue) > 0) ? "green" : "red";
var cellHtml = "<span style='color:" + color + "' originalValue='" +
cellValue + "'>" + cellValue + "</span>";
return cellHtml;
}
function unformatRating(cellValue, options, cellObject) {
return $(cellObject.html()).attr("originalValue");
}
CUSTOM;
$grid->setJSCode($image);
$grid->setSelect('stage', "SELECT id, name FROM selection where statid=1");
$grid->setSelect('status', "SELECT id,name FROM selection where statid=2 ");
$grid->setColProperty("threadid", array( "width"=>80 , "align"=>center));
$grid->setColProperty("stage", array( "width"=>120 , "align"=>center));
$grid->setColProperty("forumid", array( "width"=>0 ,));
$grid->setColProperty("status", array( "width"=>120 , "align"=>center ));
$grid->setColProperty("title", array( "width"=>280, "align"=>center ,"formatter"=>"showlink","formatoptions"=>array("baseLinkUrl"=>"showthread.php", "target"=>"_blank", "idName"=>"t")));
$grid->setColProperty("startdate", array("width"=>130,"align"=>center,
"formatter"=>"date",
"formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y")
)
);
$grid->setColProperty("duedate", array("width"=>130,"align"=>center,
"formatter"=>"date",
"formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"m/d/Y")
)
);
$grid->setColProperty("CustomerID", array("editrules"=>array("required"=>true)));
$grid->setAutocomplete("CustomerID",false,"SELECT CustomerID, CompanyName FROM customers WHERE CompanyName LIKE ? ORDER BY CompanyName",null,true,true);
$grid->setUserTime("m/d/Y");
$grid->setUserDate("m/d/Y");
$grid->setDatepicker("startdate",array("buttonOnly"=>false));
$grid->datearray = array('startdate');
$grid->setUserTime("m/d/Y");
$grid->setUserDate("m/d/Y");
$grid->setDatepicker("duedate",array("buttonOnly"=>false));
$grid->datearray = array('duedate');
$grid->navigator = true;
$grid->setNavOptions('navigator', array("cloneToTop"=>true,"excel"=>true,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
$grid->exportfile = 'Report.xls';
$grid->setNavOptions('navigator', array("cloneToTop"=>true,"pdf"=>true,"add"=>false,"edit"=>false,"del"=>false,"view"=>false));
$grid->inlineNav = true;
$grid->setNavEvent('edit', 'onInitializeForm', $upload);
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
What SQL engine are you using? If it's MySQL you can use:
echo mysql_error();
after running the select to see what error you're having
also try echoing the SELECT statement after generating it to make sure no additional whitespace etc is added to $fid