The magento 1.8 ajax cart is showing product not found error
The java script I used is
function setLocationAjax(url,id){
var data = jQuery('#product_addtocart_form').serialize();
data += '&isAjax=1';
url = url.replace("checkout/cart","ajax/index");
jQuery('#ajax_loader'+id).show();
try {
jQuery.ajax( {
url : url,
dataType : 'json',
type : 'post',
data: data,
success : function(data) {
jQuery('#ajax_loader'+id).hide();
setAjaxData(data,false);
}
});
} catch (e) {
}
}
function setAjaxData(data,iframe){
if(data.status == 'ERROR'){
alert(data.message);
}else{
if(jQuery('.block-cart')){
jQuery('.block-cart').replaceWith(data.sidebar);
}
// if(jQuery('.header .links')){
// jQuery('.header .links').replaceWith(data.toplink);
// }
if(jQuery('.cart-top-container')){
//jQuery('.cart-top-container').empty();
jQuery('.cart-top-container').replaceWith(data.toplink);
}
var targetUrl='<?php echo Mage::getUrl('onestepcheckout') ?>';
jQuery( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Checkout": function() {
window.location.href = targetUrl;
jQuery(this).dialog( "close" );
},
"Continue Shopping": function() {
jQuery(this).dialog( "close" );
}
}
});
}
}
The product is failing to get the product information required to add to cart. Is there any way to add the product to cart other than this code?
*The form is *
<form action="<?php echo $this->getSubmitUrl($p) ?>" method="post" id="product_addtocart_form"<?php if ($p->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<div class="home-prouduct-details">
<?php $pid = $p->getId(); ?>
<?php $prod = Mage::getModel('catalog/product')->load($pid); ?>
<?php $html= $prod->getShortDescription(); ?>
<?php
$str = $html;
$matches = array();
preg_match_all('#<div[^>]*>(.*?)</div>#', $str, $matches);
// print_r($matches[1][0]);
?>
<a class="prod-name" href="<?php echo $prod->getProductUrl(); ?>"><?php echo $prod->getName(); ?></a>
<div class="prod-img">
<a href="<?php echo $prod->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($prod, 'small_image'), null, true) ?>" class="product-image">
<img src="<?php echo $this->helper('catalog/image')->init($prod, 'small_image')->resize(285,172); ?>" width="285" height="175" alt="<?php echo $this->stripTags($this->getImageLabel($prod, 'small_image'), null, true) ?>" />
</a>
</div>
<div class="home-price-button">
<?php $almost_gone_qty=$this->htmlEscape($prod->getData('almost_gone_qty')); ?>
<?php $qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($prod)->getQty(); ?>
<?php if (!$this->hasOptions() && strtotime($prod->getDealEndDate())>= Mage::getModel('core/date')->timestamp(time())):?>
<div style="clear:both;"></div>
<div class="add-to-box">
<?php if($prod->isSaleable() && $qtyStock > $almost_gone_qty){ ?>
<p class="availability out-of-stock">
<a onclick="setLocationAjax('/checkout/cart/add/product/<?php echo $prod; ?>',<?php echo $prod->getId();?>)" title="Add To Cart">
<img src="<?php echo $this->getSkinUrl('images/steamy.png'); ?>" title="Add To Cart" alt="Add To Cart" width="285" />
</a>
</p>
<?php } else if($qtyStock <= $almost_gone_qty && $qtyStock!=0){?>
<p class="availability out-of-stock">
<a onclick="setLocationAjax('/checkout/cart/add/product/?<?php echo $prod; ?>',<?php echo $prod->getId();?>)" title="Almost Gone">
<img src="<?php echo $this->getSkinUrl('images/almostgone.png'); ?>" title="Almost Gone" alt="Almost Gone" width="285" />
</a>
</p>
<?php } else{ ?>
<p class="availability out-of-stock">
<a href="<?php echo Mage::getBaseUrl(); ?>sold-out" title="Sold Out">
<img src="<?php echo $this->getSkinUrl('images/soldout.png'); ?>" width="285" /><?php //echo $this->__('Out of stock') ?>
</a>
</p>
<?php } ?>
<span id='ajax_loader<?php echo $prod->getId()?>' style='text-align: center; display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>
</div>
<?php else : ?>
<p class="deal-has-ended">
<a href="<?php echo Mage::getBaseUrl(); ?>sold-out" title="Sold Out">
<img src="<?php echo $this->getSkinUrl('images/deal_ended.png'); ?>" width="285" />
</a>
</p>
<?php endif; ?>
<?php //echo $this->getChildHtml('addto') ?>
<?php //echo $this->getChildHtml('extra_buttons') ?>
</div>
<div class="home-price">
<div class="home-prices">
<?php
echo Mage::helper('core')->currency($prod->getPrice());
?>
</div>
<?php if($matches[1][1] !=""){ ?>
<div class="home-save">
<?php
$savings = $matches[1][1];
$savings = str_ireplace('Rs.', '₹', $savings);
$savings = str_ireplace('Rs', '₹', $savings);
echo $savings;
?>
<?php //print_r($matches[1][1]); ?>
<div class="home-saver">
savings
</div>
</div>
<?php } ?>
<div class="deal-endtime">
<?php
echo "<div id='cdcontainer_".$prod->getId()."' class='cdcontainer'></div>";
$dealEndDate = $prod->getDealEndDate();
$dealEndDateParts = explode(" ", $dealEndDate);
$targetDateParts = explode("-", $dealEndDateParts[0]);
$year = $targetDateParts[0];
$month = $targetDateParts[1];
$date = $targetDateParts[2];
$month_array = array(
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
);
$month = $month_array[$month-1];
$targetDate = "$month $date, $year ".$dealEndDateParts[1];
$timer_text = Mage::getStoreConfig('homedeals/basic_settings/cd_display_text');
$timer_end_text = Mage::getStoreConfig('homedeals/basic_settings/cd_end_text');
//echo $timer_end_text;
//echo date("Y-m-d H:i:s"); echo "<br/>";
//echo $dealEndDate;
if($dealEndDate <= date("Y-m-d H:i:s")){
?>
<script type="text/javascript">
var launchdate_<?php echo $prod->getId(); ?>=new cdLocalTime("cdcontainer_<?php echo $_product->getId(); ?>", "server-php", 0, "", "", "<?php echo '<span><h1 style=color:red;>Deal has ended - 00:00:00</h1></span>' ?><?php //echo $timer_text; ?>", "<?php echo $timer_end_text; ?>", "<?php echo $prod->getId(); ?>");
launchdate_<?php echo $prod->getId(); ?>.displaycountdown("hours", formatresults2);
</script>
<?php }else { ?>
<script type="text/javascript">
var launchdate_<?php echo $prod->getId(); ?>=new cdLocalTime("cdcontainer_<?php echo $prod->getId(); ?>", "server-php", 0, "<?php echo $targetDate?>", "<?php print date("F d, Y H:i:s", Mage::getModel('core/date')->timestamp(time()))?>", "<?php echo $timer_text; ?>", "<?php echo $timer_end_text; ?>", "<?php echo $prod->getId(); ?>");
launchdate_<?php echo $prod->getId(); ?>.displaycountdown("hours", formatresults2);
</script>
<?php } ?>
</div>
</div>
</div>
<div id="dialog-confirm" style="display:none;">
<?php echo $prod->getName();?> added to your cart Successfully.
</div>
</form>
There is also an URL issue I guess Thanks in advance.
my controller code is
protected function _getProduct($productInfo)
{
$product = null;
if ($productInfo instanceof Mage_Catalog_Model_Product) {
$product = $productInfo;
} elseif (is_int($productInfo) || is_string($productInfo)) {
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load($productInfo);
}
$currentWebsiteId = Mage::app()->getStore()->getWebsiteId();
if (!$product
|| !$product->getId()
|| !is_array($product->getWebsiteIds())
|| !in_array($currentWebsiteId, $product->getWebsiteIds())
) {
Mage::throwException(Mage::helper('checkout')->__('The product could not be found.'));
}
return $product;
}
/**
* Get request for product add to cart procedure
*
* #param mixed $requestInfo
* #return Varien_Object
*/
protected function _getProductRequest($requestInfo)
{
if ($requestInfo instanceof Varien_Object) {
$request = $requestInfo;
} elseif (is_numeric($requestInfo)) {
$request = new Varien_Object(array('qty' => $requestInfo));
} else {
$request = new Varien_Object($requestInfo);
}
if (!$request->hasQty()) {
$request->setQty(1);
}
return $request;
}
/**
* Add product to shopping cart (quote)
*
* #param int|Mage_Catalog_Model_Product $productInfo
* #param mixed $requestInfo
* #return Mage_Checkout_Model_Cart
*/
public function addProduct($productInfo, $requestInfo=null)
{
$product = $this->_getProduct($productInfo);
$request = $this->_getProductRequest($requestInfo);
$productId = $product->getId();
if ($product->getStockItem()) {
$minimumQty = $product->getStockItem()->getMinSaleQty();
//If product was not found in cart and there is set minimal qty for it
if ($minimumQty && $minimumQty > 0 && $request->getQty() < $minimumQty
&& !$this->getQuote()->hasProductId($productId)
){
$request->setQty($minimumQty);
}
}
if ($productId) {
try {
$result = $this->getQuote()->addProduct($product, $request);
} catch (Mage_Core_Exception $e) {
$this->getCheckoutSession()->setUseNotice(false);
$result = $e->getMessage();
}
/**
* String we can get if prepare process has error
*/
if (is_string($result)) {
$redirectUrl = ($product->hasOptionsValidationFail())
? $product->getUrlModel()->getUrl(
$product,
array('_query' => array('startcustomization' => 1))
)
: $product->getProductUrl();
$this->getCheckoutSession()->setRedirectUrl($redirectUrl);
if ($this->getCheckoutSession()->getUseNotice() === null) {
$this->getCheckoutSession()->setUseNotice(true);
}
Mage::throwException($result);
}
} else {
Mage::throwException(Mage::helper('checkout')->__('The product does not exist.'));
}
Mage::dispatchEvent('checkout_cart_product_add_after', array('quote_item' => $result, 'product' => $product));
$this->getCheckoutSession()->setLastAddedProductId($productId);
return $this;
}
/**
* Adding products to cart by ids
*
* #param array $productIds
* #return Mage_Checkout_Model_Cart
*/
public function addProductsByIds($productIds)
{
$allAvailable = true;
$allAdded = true;
if (!empty($productIds)) {
foreach ($productIds as $productId) {
$productId = (int) $productId;
if (!$productId) {
continue;
}
$product = $this->_getProduct($productId);
if ($product->getId() && $product->isVisibleInCatalog()) {
try {
$this->getQuote()->addProduct($product);
} catch (Exception $e){
$allAdded = false;
}
} else {
$allAvailable = false;
}
}
if (!$allAvailable) {
$this->getCheckoutSession()->addError(
Mage::helper('checkout')->__('Some of the requested products are unavailable.')
);
}
if (!$allAdded) {
$this->getCheckoutSession()->addError(
Mage::helper('checkout')->__('Some of the requested products are not available in the desired quantity.')
);
}
}
return $this;
}
You are doing .serialize() on a form element which doesn't have any input elememts. There is a note given http://api.jquery.com/serialize/ about which elements will be serialized using the function.
In setLocationAjax function, you are getting product id. Just pass the product id to the php script.
ie,
jQuery.ajax( {
url : url,
dataType : 'json',
type : 'post',
data: { productId: id },
success : function(data) {
jQuery('#ajax_loader'+id).hide();
setAjaxData(data,false);
}
});
In magento, you can get the product based on the productId and add to cart.
Related
Here is my php file:
<div id="map_wrap">
<div id="map"></div>
</div><!-- #map_wrap -->
<?php
$states_list = get_state_list();
$states_to_disable = get_field( 'states_to_disable' );
?>
<ul class="state-list">
<?php
foreach( $states_list as $key => $value ){
$anchor = $key;
$class = '';
foreach( $states_to_disable as $state ){
if( $state['value'] === $key ){
$class = 'disabled';
$anchor = 'no-service';
}
}
$anchor = str_replace("_","-",$anchor);
?>
<li><a class="<?= $class; ?>" href="<?php echo site_url(); ?>/<?= $anchor; ?>-quick-online-installment-loans"><?= $value; ?></a></li>
<?php
}
?>
</ul>
<?php
?>
<script src='<?php echo get_stylesheet_directory_uri(); ?>/js/raphael-min.js'></script>
<script src='<?php echo get_stylesheet_directory_uri(); ?>/js/usmap.js'></script>
<script>
$(document).ready(function() {
var clickGo = true;
$('#map').usmap({
stateStyles: {fill: '#009a4d','stroke': '#ffffff'},
stateSpecificStyles: {
<?php
foreach( $states_to_disable as $state ){
echo $state['value'] . ": {fill: '#C5C5C5'},";
}
?>
},
stateSpecificLabelBackingHoverStyles: {
<?php
foreach( $states_to_disable as $state ){
echo $state['value'] . ": {fill: '#888'},";
}
?>
},
clickState: {
<?php
foreach( $states_to_disable as $state ){
?>
'<?= $state['value']; ?>' : function(event, data) {
var state_name = data.name;
console.log('1');
clickGo = false;
state_name = state_name.replace("_","-")+'';
location.href = "<?php echo site_url(); ?>/state-terms-and-rates/no-service";
},
<?php
}
?>
},
click: function(event, data) {
var state_name = data.name;
console.log('2');
state_name = state_name.replace("_","-")+'';
if( clickGo === true ){
location.href = "<?php echo site_url(); ?>/state-terms-and-rates/"+state_name;
}
},
});
});
</script>
As you can see, in the very last section of code, any active states in the map that are clicked on, go to /state-terms-and-rates/+state_name. However, I need it to go to /+state_name-quick-online-installment-loans.
I can get it very close but the URL either shows a blank state name, the word array, a zero, or a plus sign depending on the different things I've been trying.
Can anybody give me the right direction to go in?
I tried many codes to do the thing, but it's not working.
The Image code is in the line 21. This is a copy of the code where I have to add the next and previous buttons:
<?php
defined ('_JEXEC') or die('Restricted access');
$par = JComponentHelper::getParams( 'com_djclassifieds' );
$app = JFactory::getApplication();
$item = $this->item;
$main_img_width = $par->get('gallery_width','200')-4;
$thumbs_limit = $par->get('gallery_thumbs_in_row','3');
$thumb_width = round(($par->get('gallery_width','200')/$thumbs_limit)-14);
$djMediaTools = ($par->get('djmediatools_integration', 0) == '1' && $par->get('djmediatools_album_item', 0) > 0) ? $par->get('djmediatools_album_item', 0) : false;
$djMediaToolsMinimum = (int)$par->get('djmediatools_minimum', 1);
JHtml::_('jquery.framework');
?>
<div class="images_wrap" style="width:<?php echo $par->get('gallery_width','200');?>px"><div class="images">
<?php if ($djMediaTools > 0 && count($this->item_images) >= $djMediaToolsMinimum) {?>
<div class="djc_images">
<?php echo JHtml::_('content.prepare', '{djmedia '.(int)$djMediaTools.'}', $par, 'com_djclassifieds.item.djmediatools'); ?>
</div>
<?php } else { ?>
<div class="djc_images">
<div class="djc_mainimage">
<?php if(count($this->item_images)){ ?>
<a id="djc_mainimagelink" rel="djc_lb_0" title="<?php echo $item->name; ?>" href="<?php echo JURI::base(true).$this->item_images[0]->thumb_b; ?>">
<img id="djc_mainimage" alt="<?php echo $item->name; ?>" src="<?php echo JURI::base(true).$this->item_images[0]->thumb_b;?>" />
</a>
<?php }else{?>
<?php if($par->get('blank_img_source','0')==1){ ?>
<img id="djc_mainimage" class="djc_mainimage_no_image" style="width:<?php echo $par->get('gallery_width','200');?>px" alt="<?php echo $item->name; ?>" src="<?php echo DJClassifiedsImage::getCatImage($item->cat_id);?>" />
<?php }else{ ?>
<img id="djc_mainimage" class="djc_mainimage_no_image" style="width:<?php echo $par->get('gallery_width','200');?>px" alt="<?php echo $item->name; ?>" src="<?php echo JURI::base(true).$par->get('blank_img_path','/components/com_djclassifieds/assets/images/').'no-image-big.png';?>" />
<?php } ?>
<?php }?>
</div>
<?php
if (count($this->item_images) > 1) { ?>
<div class="djc_thumbnails djc_thumbs_gal<?php echo $thumbs_limit;?> " id="djc_thumbnails">
<?php foreach($this->item_images as $im=>$img){
if($im>0 && $im%$thumbs_limit==0){
$new_row_class = ' new_row';
}else{
$new_row_class = '';
}
?>
<div class="djc_thumbnail djc_thumb_row<?php echo $new_row_class;?>">
<a rel="<?php echo JURI::base(true).$img->thumb_b;?>" title="<?php echo $img->caption; ?>" href="<?php echo JURI::base(true).$img->thumb_b;?>">
<img alt="<?php echo $img->caption; ?>" src="<?php echo JURI::base(true).$img->thumb_s;?>" />
</a>
</div>
<?php } ?>
<div class="clear_both"></div>
</div>
<?php } ?>
<?php for($ii=0; $ii<count($this->item_images);$ii++ ){ ?>
<a id="djc_lb_<?php echo $ii; ?>" class="lightbox-djitem" rel="lightbox-djitem" title="<?php echo $this->item_images[$ii]->caption;?>" href="<?php echo JURI::base(true).$this->item_images[$ii]->thumb_b;?>" style="display: none;"></a>
<?php } ?>
</div>
<?php } ?>
</div></div>
<script type="text/javascript">
this.DJCFImageSwitcher = function (){
var mainimagelink = document.id('djc_mainimagelink');
var mainimage = document.id('djc_mainimage');
var thumbs = document.id('djc_thumbnails') ? document.id('djc_thumbnails').getElements('img') : null;
var thumblinks = document.id('djc_thumbnails') ? document.id('djc_thumbnails').getElements('a') : null;
<?php if($par->get('lightbox_type','slimbox')!='magnific'){ ?>
if(mainimagelink && mainimage) {
mainimagelink.removeEvents('click').addEvent('click', function(evt) {
var rel = mainimagelink.rel;
document.id(rel).fireEvent('click', document.id(rel));
//if(!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
return false;
//}
//return true;
});
}
<?php } ?>
if (!mainimage || !mainimagelink || !thumblinks || !thumbs) return false;
thumblinks.each(function(thumblink,index){
var fx = new Fx.Tween(mainimage, {link: 'cancel', duration: 200});
thumblink.addEvent('click',function(event){
event.preventDefault();
//new Event(element).stop();
/*
mainimage.onload = function() {
fx.start('opacity',0,1);
};
*/
var img = new Image();
img.onload = function() {
fx.start('opacity',0,1);
};
fx.start('opacity',1,0).chain(function(){
mainimagelink.href = thumblink.href;
mainimagelink.title = thumblink.title;
mainimagelink.rel = 'djc_lb_'+index;
img.src = thumblink.rel;
mainimage.src = img.src;
mainimage.alt = thumblink.title;
});
return false;
});
});
};
window.addEvent('load', function(){
var img_width = document.id('dj-classifieds').getElement('.djc_images').getSize().x;
var dj_item = document.id('dj-classifieds').getElement('.djcf_images_generaldet_box').getSize().x;
var general_det = dj_item-img_width-1;
if(general_det<150){
document.id('dj-classifieds').getElement('.general_det').addClass('general_det_s');
}
if(general_det<301){
document.id('dj-classifieds').getElement('.general_det').addClass('general_det_m');
}
document.id('dj-classifieds').getElement('.general_det').setStyle('width',general_det) ;
});
window.addEvent('domready', function(){
DJCFImageSwitcher();
});
</script>
<?php if($par->get('lightbox_type','slimbox')=='magnific'){ ?>
<script type="text/javascript">
!function($){
$(document).ready(function(){
$('#djc_mainimagelink').click(function(e) {
e.preventDefault();
var rel = $(this).attr('rel');
console.log(rel);
$('#'+rel).click();
//console.log(e);
//do other stuff when a click happens
});
$('.lightbox-djitem').magnificPopup({
//$(this).magnificPopup({
// delegate: '.dj-slide-link', // the selector for gallery item
type: 'image',
mainClass: 'mfp-img-mobile',
gallery: {
enabled: true
},
image: {
verticalFit: true,
titleSrc: 'title'
},
iframe: {
patterns: {
youtube: null,
vimeo: null,
link: {
index: '/',
src: '%id%'
}
}
}
// });
});
});
}(jQuery);
</script>
<?php } ?>
what should i do to fix this error ?
ERR (3): Warning: Invalid argument supplied for foreach() in /app/design/adminhtml/default/default/template/canonical/canonical/edit/tab/header.phtml on line 79
<?php if ( Mage::getSingleton('admin/session')->isAllowed('admin/global_search') ): ?>
<fieldset>
<legend>Search</legend>
<span id="global_search_indicator" class="autocomplete-indicator" style="display: none">
<img src="<?php echo $this->getSkinUrl('images/ajax-loader.gif') ?>" alt="<?php echo $this->__('Loading...') ?>" class="v-middle"/>
</span>
<?php $defSearch = $this->__('Global Record Search') ?>
<input id="global_search" name="query" type="text" class="input-text" value="<?php if(!empty($query)): ?><?php echo $query ?><?php else: ?><?php echo $defSearch ?><?php endif ?>" onfocus="if(this.value=='<?php echo $defSearch ?>')this.value=''; " onblur="if(this.value=='')this.value='<?php echo $defSearch ?>';" />
<div id="global_search_autocomplete" class="autocomplete"></div>
<script type="text/javascript">
new Ajax.Autocompleter(
'global_search',
'global_search_autocomplete',
'<?php echo $this->getUrl('adminhtml/index/globalSearch') ?>',
{
paramName:"query",
minChars:2,
indicator:"global_search_indicator",
updateElement:getSelectionId,
evalJSON:'force'
}
);
function getSelectionId(li) {
location.href = li.getAttribute('url');
}
</script>
</fieldset>
<?php endif; ?>
</div>
</div>
<?php if(Mage::getStoreConfig('advanced/modules_disable_output/FME_Canonical')==0) : ?>
<?php
$product_id = Mage::app()->getRequest()->getParam('id');
$_product = Mage::getModel('catalog/product')->load($product_id);
$selected = $_product->getData('fme_canonicalurl');
$catIds = $_product->getCategoryIds();
foreach ($catIds as $key )
{
$catCollection = Mage::getResourceModel('catalog/category_collection')
->addAttributeToFilter('entity_id', $key);
foreach($catCollection as $cat)
{
$dat[] = $cat->getId();
}
}
?>
<script type="text/javascript">
window.onload = function () {
if(categories = document.getElementById("fme_canonicalurl"))
{
var categories = document.getElementById("fme_canonicalurl");
var newOption = document.createElement('option');
newOption.text = "<?php echo $_product->getUrlPath() ?>";
newOption.setAttribute('value', "<?php echo $_product->getUrlPath() ?>");
categories.appendChild(newOption);
<?php
foreach ($dat as $value ) {
echo "var newOption = document.createElement('option');";
$_category = Mage::getModel('catalog/category')->load($value);
$url = $_product->getUrlPath($_category); ?>
newOption.text = "<?php echo $url ?>" ;
newOption.setAttribute('value', '<?php echo $url ?>');
categories.appendChild(newOption);
<?php
}
?>
function setSelectedIndex(s, v) {
for ( var i = 0; i < s.options.length; i++ ) {
if ( s.options[i].value == v ) {
s.selectedIndex = i;
return;
}
}
}
setSelectedIndex(categories,"<?php echo $selected?>");
}
}
Your problem is that you're pushing data into the $dat array from within a loop, but you didn't initialize it first. In the case where no results are looped and no data is pushed to $dat, it is then undefined when you try and loop over $dat later on.
Initialize it first:
$catIds = $_product->getCategoryIds();
$dat = array();
foreach ($catIds as $key) {
$catCollection = Mage::getResourceModel('catalog/category_collection')
->addAttributeToFilter('entity_id', $key);
foreach ($catCollection as $cat) {
$dat[] = $cat->getId();
}
}
i am trying to make an ajax call to my database and refresh my list that i display from database. Actually what i need is, i have a table with data and i display them using php, now i want to update my list on the page without refresh anytime when in my table is inserting a new row.
sample code
foreach($_IL_QUERY_INTERNAL as $_IL_RESULT_DATA){
echo $_IL_RESULT_DATA->il_name; //display all the name from my table
}
For example:
In my table i have 5 names and you can see them on the page, now somene subit a form and i insert the sixth name in my table, and i want to update my list with the sith name as real time with no refreshing.
I will appreciate any help.
My complete code
<?php
session_start();
wp_enqueue_style('il_style_mode');
wp_enqueue_style('il_admin_style_mode');
wp_enqueue_scripts('jquery');
global $_IL_ID;
global $_IL_LIMIT;
global $_IL_TOTAL;
global $wpdb;
$_IL_TABLE_NAME_INTERNAL = $wpdb->prefix . "il_internal_transfer";
$_SESSION['IL_COUNT_ADMIN'] = 1;
require_once ($_SERVER["DOCUMENT_ROOT"]."/wp-content/plugins/il_mt4_client_area/il_request/il_internal_transfer/il_internal_admin/il_internal_transfer_tabs.php");
$_IL_START = 0;
$_IL_LIMIT = 10;
if( isset($_GET['paged']) ){
$_IL_ID = $_GET['paged'];
$_IL_START = ($_IL_ID-1) * $_IL_LIMIT;
}
$_IL_QUERY_INTERNAL = $wpdb->get_results( "SELECT * FROM $_IL_TABLE_NAME_INTERNAL ORDER BY il_id DESC LIMIT $_IL_START, $_IL_LIMIT");
$_IL_NUM_ROWS_INTERNAL_ALL = $wpdb->get_var( "SELECT COUNT(*) FROM $_IL_TABLE_NAME_INTERNAL");
echo '<span class="il_admin_main_title">';
echo '<span>';
echo '<h2>Internal Transfers</h2>';
echo '</span>';
echo '<span>';
require_once ($_SERVER["DOCUMENT_ROOT"]."/wp-content/plugins/il_mt4_client_area/il_request/il_internal_transfer/il_internal_admin/il_internal_transfer_sub_tabs.php");
echo '</span>';
echo '</span>';
echo '<span class="il_admin_transactions_block" id="il_admin_transactions_block">';
echo '<ul id="list">';
if( $_IL_NUM_ROWS_INTERNAL_ALL < 1 ){
include ($_SERVER["DOCUMENT_ROOT"]."/wp-content/plugins/il_mt4_client_area/il_include/il_messages/il_internal_transfer_sorry.php");
}else{
foreach($_IL_QUERY_INTERNAL as $_IL_RESULT_DATA)
{
?>
<span class="il_admin_transactions_block_raw_block">
<form method="post">
<input type='hidden' name='il_transaction_id' value="<?php echo $_IL_RESULT_DATA->il_id ?>" />
<span class="il_admin_transactions_block_raw">
<span class="il_admin_transactions_block_raw_count"><?php echo $_SESSION['IL_COUNT_ADMIN'] ?></span>
<span class="il_admin_internal_block_raw_full_name">
<?php echo $_IL_RESULT_DATA->il_name ?>
</span>
<span class="il_admin_internal_block_raw_from_to">
<span><?php echo $_IL_RESULT_DATA->il_from_mt4 ?></span> <?php echo $_IL_RESULT_DATA->il_from_mt4_currency ?>
<img src="/wp-content/plugins/il_mt4_client_area/il_images/il_icons/il_gray_left_icon.png" class="il_arrow_between" />
<span><?php echo $_IL_RESULT_DATA->il_to_mt4 ?></span> <?php echo $_IL_RESULT_DATA->il_to_mt4_currency ?>
</span>
<span class="il_admin_internal_block_raw_email"><?php echo $_IL_RESULT_DATA->il_email ?></span>
<span class="il_admin_internal_block_raw_date"><?php echo $_IL_RESULT_DATA->il_date ?></span>
</span>
<span class="il_admin_transactions_block_raw_extras">
<?php if( $_IL_RESULT_DATA->il_comments === NULL || empty($_IL_RESULT_DATA->il_comments) ){ ?>
<?php } else { ?>
<span class="il_admin_transactions_block_raw_comment">
<span>Comment:</span>
<span><?php echo $_IL_RESULT_DATA->il_comments ?></span>
</span>
<?php } ?>
<?php if( $_IL_RESULT_DATA->il_status == 'approved' ){ ?>
<?php } else { ?>
<span class="il_admin_transactions_block_raw_extras_status_icon">
<img src="/wp-content/plugins/il_mt4_client_area/il_images/il_icons/il_green_status_<?php echo $_IL_RESULT_DATA->il_status ?>_icon.gif" alt="Processing" title="Processing"/>
</span>
<?php } ?>
<span class="il_admin_transactions_block_raw_extras_ip">
The transaction was done from this ip <?php echo $_IL_RESULT_DATA->il_user_ip ?>
</span>
<span class="il_admin_transactions_block_raw_extras_ip_select">
<?php if( $_IL_RESULT_DATA->il_status == 'approved' ){ ?>
<span class="il_admin_transactions_block_raw_extras_status_<?php echo $_IL_RESULT_DATA->il_status ?>"><?php echo $_IL_RESULT_DATA->il_status ?></span>
<img src="/wp-content/plugins/il_mt4_client_area/il_images/il_icons/il_green_status_<?php echo $_IL_RESULT_DATA->il_status ?>_icon.gif" alt="Processing" title="Processing" width="20"/>
<?php } else { ?>
<span class="il_admin_transactions_block_raw_extras_update">
<select name="il_status_new">
<option>approved</option>
<option>waiting</option>
<option>rejected</option>
</select>
</span>
<span class="il_admin_transactions_block_raw_extras_update_button">
<input type="submit" name="il_status_update" value="update status" />
<input type="submit" name="il_delete" value="delete" class="il_admin_transactions_delete_button" />
</span>
<?php } ?>
</span>
</span>
<span class="il_clear"></span>
</form>
</span>
<?php
$_SESSION['IL_COUNT_ADMIN']++;
}
}
echo '</ul>';
echo '</span>';
if(isset($_POST['il_status_update'])){
$wpdb->update(
$_IL_TABLE_NAME_INTERNAL,
array(
'il_status' => $_POST['il_status_new'],
),
array( 'il_id' => $_POST['il_transaction_id'] ),
array(
'%s',
),
array( '%s' )
);
};
if(isset($_POST['il_delete'])){
$wpdb->delete( $_IL_TABLE_NAME_INTERNAL, array( 'il_id' => $_POST['il_transaction_id'] ), array( '%d' ) );
};
$_IL_ROWS_COUNT = mysql_num_rows(mysql_query("select * from $_IL_TABLE_NAME_INTERNAL"));
$_IL_TOTAL = ceil( $_IL_ROWS_COUNT / $_IL_LIMIT );
if($_IL_LIMIT < $_IL_ROWS_COUNT){
echo '<span class="il_pagination_block_admin">';
if( $_IL_ID > 1 )
{
echo "<a href='?page=il_internal_transfer&tab=il_internal_transfer&paged=".($_IL_ID-1)."' class='il_pagination_prev'><span class='il_pagination_prev_icon'></span></a>";
}
echo "<ul class='il_pagination'>";
for( $i = 1; $i <= $_IL_TOTAL; $i++ )
{
if( $i == $_IL_ID ) { echo "<li class='il_pagination_current'>".$i."</li>"; }
else { echo "<li><a href='?page=il_internal_transfer&tab=il_internal_transfer&paged=".$i."'>".$i."</a></li>"; }
}
echo "</ul>";
if( $_IL_ID != $_IL_TOTAL )
{
echo "<a href='?page=il_internal_transfer&tab=il_internal_transfer&paged=".( $_IL_ID + 1 )."' class='il_pagination_next'><span class='il_pagination_next_icon'></span></a>";
}
echo "</span>";
}else{
}
?>
<script>
jQuery( document ).ready(function($) {
function fetch(){
$.ajax({
url: '/wp-content/plugins/il_mt4_client_area/il_request/il_internal_transfer/il_internal_admin/il_internal_transfer.php',
success: function(data) {
$(data).hide().prependTo("#list").slideDown("slow");
if($("#list li").length > 15){
$('#list li:gt(14)').remove();
}
setTimeout("fetch()", 5000);
}
});
}
});
</script>
Use this JS code for live updating your result. Code will append new result at the top.
JS CODE
function fetch(){
$.ajax({
url: 'PATH-TO_FILE',
success: function(data) {
$(data).hide().prependTo("#list").slideDown("slow");
if($("#list li").length > 15){
$('#list li:gt(14)').remove();
}
setTimeout("fetch()", 5000);
}
});
}
HTML CODE
<ul id="list">
<?php
foreach($_IL_QUERY_INTERNAL as $_IL_RESULT_DATA){
echo $_IL_RESULT_DATA->il_name; //display all the name from my table
}
?>
</ul>
the server gave me this error but i can't understand why!
The error is
"Parse error: syntax error, unexpected end of file in /homepages/43/d514350324/htdocs/wp-content/plugins/NetClass/nw_NetClass_init_CustomBoxes.php on line 227"
Line 227 is the last line of the file.
That's the code. Help me please!
<?php
/* Define the custom box */
add_action( 'add_meta_boxes', 'aggiungiMetaBox' );
add_action( 'save_post', 'salvaMetaBox', 10, 2 );
add_action( 'wp_ajax_nc_savePortable_lezioni_action', 'nc_savePortable_lezioni' );
add_action( 'admin_footer', 'nc_savePortable_lezioni_js' );
function parseInt($str){
return (int) $str;
}
function aggiungiMetaBox(){
add_meta_box( "nw_Netclass_Box_AggiungiaCorso", "Aggiungi la lezione al corso", "aggiungiMetaBox_AggiungiLezione", "corso");
add_meta_box("nw_NetClass_Box_DatiFattura", "Dati della fattura", "aggiungiMetaBox_DatiFattura", "fattura");
add_meta_box("nw_NetClass_Box_Corsi_Associati", "Corsi associati", "aggiungiMetaBox_Corsi_Associati", "lezione");
}
function aggiungiMetaBox_Corsi_Associati($post){
?>
<p><?php echo get_post_meta($post->ID, 'corsi_associati',true); ?></p>
<?php
}
function is_in_array($array_lezioni_del_corso, $object){
if(!is_array($array_lezioni_del_corso)){
if($array_lezioni_del_corso == $object){
return true;
}else{
return false;
}
}
else{
return in_array($object, $array_lezioni_del_corso);
}
}
function aggiungiMetaBox_DatiFattura($post){
$post_id = $post->ID;
$user_info = get_userdata(get_post_meta($post_id, "intestatarioFattura" , true));
$user_meta = array(
'tipo_utente' => get_user_meta(get_post_meta($post_id, "intestatarioFattura" , true), 'tipo_utente',true),
'p_iva' => get_user_meta(get_post_meta($post_id, "intestatarioFattura" , true), 'p_iva',true),
'indirizzo_fatturazione' => get_user_meta(get_post_meta($post_id, "intestatarioFattura" , true), 'indirizzo_fatturazione',true)
);
?>
Intestatario della fattura : <?php echo $user_info->display_name; ?> <br>
Tipo di utente : <?php echo $user_meta['tipo_utente']; ?> <br>
Indirizzo di fatturazione : <?php echo $user_meta['indirizzo_fatturazione']; ?> <br>
P.IVA : <?php echo $user_meta['p_iva']; ?> <br>
Inponibile della fattura : <?php echo get_post_meta( $post_id, "inponibileFattura" , true); ?> <br>
Totale della fattura : <?php echo get_post_meta( $post_id, "totaleFattura" , true); ?> <br>
Articoli acquistati:
<ul>
<?php
foreach(get_post_meta( $post_id, "articoliFattura" , true) as $prodotto){
?>
<li><?php echo get_the_title($prodotto); ?></li>
<?php
}
?>
</ul>
<?php
}
//save the meta box
function salvaMetaBox($post_id)
{
//Salvo i dati del Box lezioni nel post corso //
global $wpdb;
$database_name = $wpdb->prefix.'Netclass_friends';
if ( (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || ( defined('DOING_AJAX') && DOING_AJAX) || isset($_REQUEST['bulk_edit']) ) { return $post_id; }
//Salvo i dati delle fatture
}
function aggiungiMetaBox_AggiungiLezione($post){
global $wpdb;
$post_id = $post->ID;
$query = "SELECT post_title,ID FROM ".$wpdb->prefix."posts WHERE post_type='lezione' AND post_status='publish'";
$array_lezioni_del_corso = get_post_meta($post_id, 'array_lezioni_del_corso');
$lezioni = $wpdb->get_results($query);
foreach ($lezioni as $lezione) { ?>
<input id="<?php echo $lezione->ID; ?>" data-title="<?php echo $lezione->post_title; ?>" class="nc_lezione_pubblicata" type="checkbox" name="checkfield[]" value="<?php echo $lezione->ID; ?>" <?php if ( is_in_array($array_lezioni_del_corso[0], $lezione->ID)) { ?> checked <?php } ?>/>
<label for="<?php echo $lezione->ID; ?>"><?php echo $lezione->post_title; ?></label> <br>
<?php } ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function($)
{
$( '.sortable' ).sortable({
opacity: 0.6,
revert: true,
cursor: 'move',
handle: '.hndle',
placeholder: {
element: function(currentItem) {
return $("<li style='background:#E7E8AD'> </li>")[0];
},
update: function(container, p) {
return;
}
},
update: function( event, ui ) {
console.log($(".sortable").sortable("toArray", {attribute: 'data-id'}));
saveSortable($(".sortable").sortable("toArray", {attribute: 'data-id'}));
}
});
$( '.sortable' ).disableSelection();
$(".nc_lezione_pubblicata").change(function() {
if( $(this).is(':checked') ){
$( '<li class="nc_lezione_del_corso" data-id="'+$(this).attr('id')+'" id="lezione_del_corso_'+$(this).attr('id')+'"><code class="hndle"> -[]- </code>'+$(this).data('title')+'</p>' ).appendTo( ".sortable" );
}else{
$("#lezione_del_corso_"+$(this).attr('id')).remove();
console.log("elimino");
}
saveSortable($(".sortable").sortable("toArray", {attribute: 'data-id'}));
});
});
</script>
<ul class="sortable ui-sortable">
<?php foreach ($array_lezioni_del_corso[0] as $lezione_del_corso) { ?>
<li class="nc_lezione_del_corso" id="lezione_del_corso_<?php echo $lezione_del_corso; ?>"
data-id="<?php echo $lezione_del_corso; ?>">
<code class='hndle'> -[]- </code>
<?php echo get_the_title($lezione_del_corso); ?>
</li>
} ?>
</ul>
<p>
<script type="text/javascript">
$(function(){
console.log($(".sortable").sortable("toArray"));
});</script>
</p>
<?php }
function nc_savePortable_lezioni(){
global $wpdb;
$post_id = $_POST['post_id'];
$array_lezioni_del_corso = $_POST['array_lezioni_del_corso'];
update_post_meta($post_id, 'array_lezioni_del_corso', $array_lezioni_del_corso);
foreach ($array_lezioni_del_corso as $lezione_del_corso) {
$corsi_associati = get_post_meta($lezione_del_corso, 'corsi_associati', true);
$corsi_associati = $corsi_associati.','.$post_id;
update_post_meta(parseInt($lezione_del_corso), 'corsi_associati', $corsi_associati);
}
echo 'al server arrriva '.$array_lezioni_del_corso;
}
function nc_savePortable_lezioni_js(){
?>
<script type="text/javascript">
function saveSortable(sortableArraystringData){
var data = {
action: 'nc_savePortable_lezioni_action',
array_lezioni_del_corso : sortableArraystringData,
post_id : <? echo get_the_ID(); ?>
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('This was passed ' + sortableArraystringData);
});
}
</script>
<?php
}
You're missing a curly brace somewhere.