I am working on a simple script which is getting all the images from instagram.
And i have very strange problem with Facebook share button.
Here is my current script:
<?PHP
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$tag = Mage::getStoreConfig('vivastags/vivasgroup/instagra_tag');
$tag_additional = Mage::getStoreConfig('vivastags/vivasgroup/instagram_tag');
$client_id = "1e0f576fbdb44e299924a93cace24507";
$Next_URL = $_GET["nexturl"];
if($Next_URL == ""){
$url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id.'&count=24';
} else {
$url = $Next_URL;
}
$Next_URL_Additional = $_GET["nexturl_add"];
if($Next_URL_Additional == ""){
$url_add = 'https://api.instagram.com/v1/tags/'.$tag_additional.'/media/recent?client_id='.$client_id.'&count=24';
} else {
$url_add = $Next_URL_Additional;
}
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
$maxid = $results['pagination']['next_max_id'];
$nexturl = $results['pagination']['next_url'];
$inst_stream_add = callInstagram($url_add);
$results_add = json_decode($inst_stream_add, true);
$maxid_add = $results_add['pagination']['next_max_id'];
$nexturl_add = $results_add['pagination']['next_url'];
//Now parse through the $results array to display your results...
?>
<div class="holder" style="display:block;margin-left:70px;">
<?PHP
foreach($results['data'] as $item){
$image_link = $item['images']['thumbnail']['url'];
$big_image = $item['images']['standard_resolution']['url'];
$Profile_name = $item['user']['username'];
$PostID = $item['id'];
$Full_name = $item['user']['full_name'];
$Profile_Picture = $item['user']['profile_picture'];
$link = $item['link'];
$NotParsedString = Mage::getStoreConfig('vivastags/vivasgroup/instagra_forbiden_ids');
if(!in_array($PostID, explode(",", $NotParsedString))) {
?>
<a class="fancybox" rel="gallery1" href="#<?PHP echo $PostID;?>" id-za-premahvane="<?PHP echo $PostID;?>">
<img src="<?PHP echo $image_link; ?>" id="InstaBlock"/>
</a>
<div id="<?PHP echo $PostID;?>" style="display:none;">
<img src="<?PHP echo $big_image;?>" style="width:75%;">
<div style="display:block;clear:both;width:100%;">
<div style="display:block;width:200px;margin-top:10px;clear:both;margin-left:auto;margin-right:auto;">
<div style="display:block;">
<div class="fb-share-button" data-href="<?PHP echo $link; ?>" data-layout="button"></div>
</div>
<div style="display:block;position:absolute;margin-top:-20px;margin-left:100px;">
Tweet
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
</div>
<div style="display:block;position:absolute;margin-top:-20px;margin-left:180px;">
<a href="https://www.pinterest.com/pin/create/button/
?url=<?PHP echo $link; ?>
&media=<?PHP echo $big_image;?>
&description=Next%20stop%3A%20Pinterest"
data-pin-do="buttonPin"
target="_blank">
<img src="//assets.pinterest.com/images/pidgets/pin_it_button.png" />
</a>
</div>
</div>
<div style="display:block;margin-left:auto;margin-right:auto;margin-top:20px;">
<img src="<?PHP echo $Profile_Picture;?>" width="50px;"> <b>#<?PHP echo $Full_name;?></b>
</div>
</div>
</div>
<?PHP
}
}
foreach($results_add['data'] as $item_add){
$image_link_add = $item_add['images']['thumbnail']['url'];
$big_image_add = $item_add['images']['standard_resolution']['url'];
$Profile_name_add = $item_add['user']['username'];
$PostID_add = $item_add['id'];
$Full_name_add = $item_add['user']['full_name'];
$Profile_Picture_add = $item_add['user']['profile_picture'];
$link_add = $item_add['link'];
$NotParsedString_add = Mage::getStoreConfig('vivastags/vivasgroup/instagra_forbiden_ids');
if(!in_array($PostID_add, explode(",", $NotParsedString_add))) {
?>
<a class="fancybox" rel="gallery1" href="#<?PHP echo $PostID_add;?>" id-za-premahvane="<?PHP echo $PostID_add;?>">
<img src="<?PHP echo $image_link_add; ?>" id="InstaBlock"/>
</a>
<div id="<?PHP echo $PostID_add;?>" style="display:none;">
<img src="<?PHP echo $big_image_add;?>" style="width:75%;">
<div style="display:block;clear:both;width:100%;">
<div style="display:block;width:200px;margin-top:10px;clear:both;margin-left:auto;margin-right:auto;">
<div style="display:block;">
<div class="fb-share-button" data-href="<?PHP echo $link_add; ?>" data-layout="button"></div>
</div>
<div style="display:block;position:absolute;margin-top:-20px;margin-left:100px;">
Tweet
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
</div>
<div style="display:block;position:absolute;margin-top:-20px;margin-left:180px;">
<a href="https://www.pinterest.com/pin/create/button/
?url=<?PHP echo $link_add; ?>
&media=<?PHP echo $big_image_add;?>
&description=Next%20stop%3A%20Pinterest"
data-pin-do="buttonPin"
target="_blank">
<img src="//assets.pinterest.com/images/pidgets/pin_it_button.png" />
</a>
</div>
</div>
<div style="display:block;margin-left:auto;margin-right:auto;margin-top:20px;">
<img src="<?PHP echo $Profile_Picture_add;?>" width="50px;"> <b>#<?PHP echo $Full_name_add;?></b>
</div>
</div>
</div>
<?PHP
}
}
?>
<div id="LoadedResults"></div>
</div>
<?PHP
$nextUrlEncoded_add = urlencode($Next_URL_Additional);
$nextUrlEncoded = urlencode($nexturl);
?>
<div id="Loading">
Моля, изчакайте...
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
$(".fancybox").fancybox({
openEffect : 'none',
closeEffect : 'none',
'titlePosition' : 'inside',
'transitionIn' : 'none',
'transitionOut' : 'none'
});
var NextUrlLink = "";
var NextUrlLink_add = "";
var TimesScrolled = 0;
if (!NextUrlLink){
var nextUrl = "<?PHP echo $nexturl;?>";
}
if (NextUrlLink){
var nextUrl = NextUrlLink;
}
if (!NextUrlLink_add){
var nextUrl_add = "<?PHP echo $nexturl_add;?>";
}
if (NextUrlLink_add){
var nextUrl_add = NextUrlLink_add;
}
$(window).scroll(function() {
if (TimesScrolled < 6) {
var hT = $('.footer-banners').offset().top,
hH = $('.footer-banners').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
$('#Loading').show();
$.ajax({
url: 'getajaxlink.php',
type: 'POST',
dataType: 'html',
data: {
next_url: nextUrl
},
}).done(function ( html ) {
var data = JSON.parse(html);
NextUrlLink = data.next_url_link;
});
$.ajax({
url: 'getajaxlink_add.php',
type: 'POST',
dataType: 'html',
data: {
next_url_add: nextUrl_add
},
}).done(function ( html ) {
var datas = JSON.parse(html);
NextUrlLink_add = datas.next_url_link;
});
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'html',
data: {
next_url: nextUrl,
next_url_add: nextUrl_add
},
}).done(function ( html ) {
TimesScrolled = TimesScrolled + 1;
$('#LoadedResults').append( html);
$('#Loading').hide();
});
}
} else {
$('#LoadMore').show();
}
});
$( "#LoadMore" ).click(function() {
$('#Loading').show();
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'html',
data: {
next_url: nextUrl,
next_url_add: nextUrl_add
},
}).done(function ( html ) {
TimesScrolled = TimesScrolled + 1;
$('#LoadedResults').append( html);
$('#Loading').hide();
});
});
});
</script>
<button id="LoadMore">Зареди още..</button>
This script is loading more content when the user scrolls to div element with class footer-banners. It is calling an $.ajax function from the file ajax.php and here is the complete code for ajax.php:
<?PHP
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
$app = Mage::app();
Mage::app();
Mage::getSingleton('core/session', array('name' => 'frontend'));
ini_set('display_errors', 1);
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$client_id = "1e0f576fbdb44e299924a93cace24507";
$Next_URL = $_POST["next_url"];
$url = $Next_URL;
$Next_URL_add = $_POST["next_url_add"];
$url_add = $Next_URL_add;
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
$maxid = $results['pagination']['next_max_id'];
$nexturl = $results['pagination']['next_url'];
//Now parse through the $results array to display your results...
foreach($results['data'] as $item){
$image_link = $item['images']['thumbnail']['url'];
$big_image = $item['images']['standard_resolution']['url'];
$Profile_name = $item['user']['username'];
$PostID = $item['id'];
$Full_name = $item['user']['full_name'];
$Profile_Picture = $item['user']['profile_picture'];
$link = $item['link'];
$NotParsedString = Mage::getStoreConfig('vivastags/vivasgroup/instagra_forbiden_ids');
if(!in_array($PostID, explode(",", $NotParsedString))) {
?>
<a class="fancybox" rel="gallery1" href="#<?PHP echo $PostID;?>" id-za-premahvane="<?PHP echo $PostID;?>">
<img src="<?PHP echo $image_link; ?>" id="InstaBlock"/>
</a>
<div id="<?PHP echo $PostID;?>" style="display:none;">
<img src="<?PHP echo $big_image;?>" style="width:75%;">
<div style="display:block;clear:both;width:100%;">
<div style="display:block;width:200px;margin-top:10px;clear:both;margin-left:auto;margin-right:auto;">
<div style="display:block;">
<div class="fb-share-button" data-href="<?PHP echo $link; ?>" data-layout="button"></div>
</div>
<div style="display:block;position:absolute;margin-top:-20px;margin-left:100px;">
Tweet
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
</div>
<div style="display:block;position:absolute;margin-top:-20px;margin-left:180px;">
<a href="https://www.pinterest.com/pin/create/button/
?url=<?PHP echo $link; ?>
&media=<?PHP echo $big_image;?>
&description=Next%20stop%3A%20Pinterest"
data-pin-do="buttonPin"
target="_blank">
<img src="//assets.pinterest.com/images/pidgets/pin_it_button.png" />
</a>
</div>
</div>
<div style="display:block;margin-left:auto;margin-right:auto;margin-top:20px;">
<img src="<?PHP echo $Profile_Picture;?>" width="50px;"> <b>#<?PHP echo $Full_name;?></b>
</div>
</div>
</div>
<?PHP
}
}
$inst_stream_add = callInstagram($url_add);
$results_add = json_decode($inst_stream_add, true);
$maxid_add = $results_add['pagination']['next_max_id'];
$nexturl_add = $results_add['pagination']['next_url'];
//Now parse through the $results array to display your results...
foreach($results_add['data'] as $item_add){
$image_link_add = $item_add['images']['thumbnail']['url'];
$big_image_add = $item_add['images']['standard_resolution']['url'];
$Profile_name_add = $item_add['user']['username'];
$PostID_add = $item_add['id'];
$Full_name_add = $item_add['user']['full_name'];
$Profile_Picture_add = $item_add['user']['profile_picture'];
$link_add = $item_add['link'];
$NotParsedString = Mage::getStoreConfig('vivastags/vivasgroup/instagra_forbiden_ids');
if(!in_array($PostID_add, explode(",", $NotParsedString_add))) {
?>
<a class="fancybox" rel="gallery1" href="#<?PHP echo $PostID_add;?>" id-za-premahvane="<?PHP echo $PostID_add;?>">
<img src="<?PHP echo $image_link_add; ?>" id="InstaBlock"/>
</a>
<div id="<?PHP echo $PostID_add;?>" style="display:none;">
<img src="<?PHP echo $big_image_add;?>" style="width:75%;">
<div style="display:block;clear:both;width:100%;">
<div style="display:block;width:200px;margin-top:10px;clear:both;margin-left:auto;margin-right:auto;">
<div style="display:block;">
<div class="fb-share-button" data-href="<?PHP echo $link_add; ?>" data-layout="button"></div>
</div>
<div style="display:block;position:absolute;margin-top:-20px;margin-left:100px;">
Tweet
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
</div>
<div style="display:block;position:absolute;margin-top:-20px;margin-left:180px;">
<a href="https://www.pinterest.com/pin/create/button/
?url=<?PHP echo $link_add; ?>
&media=<?PHP echo $big_image_add;?>
&description=Next%20stop%3A%20Pinterest"
data-pin-do="buttonPin"
target="_blank">
<img src="//assets.pinterest.com/images/pidgets/pin_it_button.png" />
</a>
</div>
</div>
<div style="display:block;margin-left:auto;margin-right:auto;margin-top:20px;">
<img src="<?PHP echo $Profile_Picture_add;?>" width="50px;"> <b>#<?PHP echo $Full_name_add;?></b>
</div>
</div>
</div>
<?PHP
}
}
I have very strange problem. I am using the same code for the both files, the main and ajax.php. When elements are loaded with ajax.php the Facebook and Twitter button are not appearing as intended.
Please take a look at the live demo: http://home.cosmeosp.eu/social
Scroll to the bottom and new content will be loaded, after that click on a random picture and check out the Twitter button, because the Facebook button is not even appearing. How can i fix that and where is the problem ?
Can you help me out?
Thanks in advance!
After the ajax call is complete, call this function: FB.XFBML.parse();
For example:
... ajax call
}).done(function(data){
// do something
FB.XFBML.parse();
});
And for twitter:
twttr.widgets.load()
Related
I've been struggling to create a shopping cart using ajax. I'm new to codeigniter and ajax but it seems the request from ajax is successful since the alert('success') in success:function is working. But I can't output data from the controller. At the place where I want to output cart I just get "welcome to xamp window" Could you tell me what I'm doing wrong?
Product view:
<?php if(count($data)): ?>
<?php foreach ($data as $item) { ?>
<div class="shop-item">
<div class="image">
<a href="<?php echo base_url(); ?>index.php/items/item1">
<img class="shop-item-image" src="<?php echo base_url("uploads/".$item->image) ?>" alt="Ariana Grande: thank u, next exclusive clear/pink lp"/>
</a>
<?php if($item->status=='sold'): ?>
<p class="sold-btn">Sold out</p>
<?php else: ?>
<button class="cart-btn" data-productid="<?php echo $item->id;?>" data-productartist="<?php echo $item->artist;?>"
data-producttitle="<?php echo $item->title;?>" data-productprice="<?php echo $item->price;?>" data-productimage="<?php echo $item->image;?>">
<i class="fa fa-shopping-cart"></i>Add to cart</button>
<?php endif; ?>
</div>
<a class="artist" href="#">
<div class="shop-item-details">
<span class="brand"><?php echo $item->artist; ?></span>
</div>
</a>
<div class="title">
<span class="format double-vinyl-lp"><?php echo $item->title; ?></span>
</div>
<div>
<span class="price">€<?php echo $item->price; ?></span>
</div>
</div>
<?php } ?>
<?php endif; ?>
</div>
Jquery
$(document).ready(function() {
$('.cart-btn').click(function () {
var product_id = $(this).data("productid");
var product_artist = $(this).data("productartist");
var product_title = $(this).data("producttitle");
var product_price = $(this).data("productprice");
var image = $(this).data("productimage");
var quantity = 1;
$.ajax({
url :'/index.php/cart/add_to_cart',
method : "POST",
data : {product_id: product_id, product_artist: product_artist, product_title: product_title, product_price: product_price, quantity:quantity, image:image},
success: function(data){
alert(product_artist);
$('#detail-cart').html(data);
},
});
});
$('#detail-cart').load("<?php echo site_url('index.php/cart/load_cart');?>");
})
Controller
public function add_to_cart() {
$data = array(
'id' => $this->input->post('product_id'),
'name' => $this->input->post('product_artist'),
'price' => $this->input->post('product_price'),
'qty' =>1
//'title'=>$this->input->$_POST('product_title'),
//'image'=>$this->input->$_POST('image')
);
$this->cart->insert($data);
print_r(($this->cart->total_items()));
echo $this->show_cart();
}
public function show_cart(){
$output = '';
$no = 0;
foreach ($this->cart->contents() as $items) {
$no++;
$output .='
<div>
<a href="">
<p>hello</p>
</a>
</div>
<div class="description">
<a class="artist" href="">'.$items['name'].'</a>
<p class="mini-total"><span>'.number_format($items['qty']).'</span>×<span>'.number_format($this->cart->total()).'</span></p>
remove
</div>
<div class="quantity">
<i class="fa fa-chevron-up"></i>
<i class="fa fa-chevron-down"></i>
</div>
';
}
return $output;
}
public function load_cart(){
echo $this->show_cart();
}
}
cert view I want to display it in a different view as a part of the header
<div id="detail-cart" class="mini-cart-item">
</div>
I figured the problem. the problem was in url
url :'/index.php/cart/add_to_cart'
didn't work; neither:
url :'<?phph echo base_url();?>index.php/cart/add_to_cart
what i did was declaring :
<script>
base_url= '<?phph echo base_url();?>index.php/cart/add_to_cart'
</script>
and then set url as
url: base_url+'index.php/cart/add_to_cart'
and it worked;
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 } ?>
I am having a main page "landing.php", here in a div i am calling another page using ajax function "fetch_pages.php". In fetch_pages.php, i am loading data from db as 5 records at a time, when the user reaches the end of page then next 5 records are displayed. Thats working perfectly.
But in landing.php, when i enter a new record and reload the div, then the div content becomes blank, it doesn't show the latest content, after refreshing the full page manually then its again shows all the records. Can't understand whats wrong, kindly help.
landing.php page
<div class="mainsection">
<div>
<div class="pull-left postimage"><?php echo "<img src=profile_pic/".$ProfilePic ." />"; ?></div>
<div class="pull-left posttext">
<div class="postname"><?php echo $Name; ?></div>
<p><?php echo $UT." - ".$Designation." - ".$Company; ?></p></div>
<textarea id="posting" name="posting" rows="2" cols="50" placeholder="Share something here..."></textarea>
<div class="clear"></div>
<hr>
</div>
<div class="fileUpload btn btn-default">
<span><i class="fa fa-camera-retro" style="margin-right: 6px;" aria-hidden="true"></i>Upload Image</span>
<input type="file" class="upload" />
</div>
<div>
<input class="postall btn btn-primary pull-right" type="submit" onClick="UserPost()" value="Post">
</div>
<div class="clear"></div>
</div>
<!-- Loading User Posts -->
<div id="mainsectionID">
<div id="results"><!-- results appear here as list --></div>
</div>
<script>
(function($){
$.fn.loaddata = function(options) {// Settings
var settings = $.extend({
loading_gif_url : "images/ajax-loader.gif", //url to loading gif
end_record_text : 'No more records found!', //no more records to load
data_url : 'fetch_pages.php', //url to PHP page
start_page : 1 //initial page
}, options);
var el = this;
loading = false;
end_record = false;
contents(el, settings); //initial data load
$(window).scroll(function() { //detact scroll
if($(window).scrollTop() + $(window).height() >= $(document).height()){ //scrolled to bottom of the page
contents(el, settings); //load content chunk
}
});
};
//Ajax load function
function contents(el, settings){
var load_img = $('<img/>').attr('src',settings.loading_gif_url).addClass('loading-image'); //create load image
var record_end_txt = $('<div/>').text(settings.end_record_text).addClass('end-record-info'); //end record text
if(loading == false && end_record == false){
loading = true; //set loading flag on
el.append(load_img); //append loading image
$.post( settings.data_url, {'page': settings.start_page}, function(data){ //jQuery Ajax post
if(data.trim().length == 0){ //no more records
el.append(record_end_txt); //show end record text
load_img.remove(); //remove loading img
end_record = true; //set end record flag on
return; //exit
}
loading = false; //set loading flag off
load_img.remove(); //remove loading img
el.append(data); //append content
settings.start_page ++; //page increment
})
}
}
})(jQuery);
$("#results").loaddata(); //load the results into element
</script>
fetch_pages.php code-
<?php
session_start();
include 'db.php'; //include config file
$UserID=$_SESSION['uid'];
$UserType=$_SESSION['utype'];
$GLOBALS['lks']=0;
$GLOBALS['cmnts']=0;
$GLOBALS['disabled']="";
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
?>
<!---post start -->
<?php
//fetch records using page position and item per page.
$results = $linkID1->query("select slno,posts,img_link,video_link,likes,comments,shares,post_date,post_time,UserID from user_posts where UserID='$UserID' or UserID in(select MyFriendsUserID from user_connections where MyUserID='$UserID') or UserID in(select MyUserID from user_connections where MyFriendsUserID='$UserID') order by slno desc LIMIT $position, $item_per_page")
or
die(mysqli_error());
//output results from database
?>
<?php
while($row = mysqli_fetch_array($results))
{ //fetch values
$CUID=$row['UserID'];
$stmt = $linkID1->prepare("select Name,Company,Designation,UserType from user_details where UserID=?");
$stmt->bind_param("s", $CUID);
$stmt->execute();
$stmt->bind_result($Name2,$Company2,$Designation2,$UType);
$stmt->fetch();
$stmt->close();
$UT2='';
if($UType=='A')
{
$UT2='Advertiser';
}
else if($UType=='P')
{
$UT2='Publisher';
}
$stmt = $linkID1->prepare("select ProfilePic from user_picture where UserID=?");
$stmt->bind_param("s", $CUID);
$stmt->execute();
$stmt->bind_result($PPic);
$stmt->fetch();
$stmt->close();
?>
<div class="mainsection">
<div>
<div class="pull-left postimage"><?php echo "<img src=profile_pic/".$PPic ." />"; ?></div>
<div class="pull-left posttext">
<div class="postname"><?php echo $Name2; ?></div>
<p><?php echo $UT2." - ".$Designation2." - ".$Company2; ?></p></div>
<div class="clear"></div>
<div class="postdowntxt"><p><?php echo $row['posts']; ?></p></div>
<hr>
</div>
<div class="btnclasess" id="likescommentID<?php echo $row[slno]; ?>">
<div class="likescomment"><?php dataLC($linkID1, $row['slno'],$CUID); ?><a style="padding-right: 7px" href="#"><?php if($GLOBALS['lks']==0){echo '';}else{ echo $GLOBALS['lks']." Likes"; } ?></a><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?></div>
<div class="pull-left likebtn"><button <?php echo $disabled; ?> class="btn" id="likeButton<?php echo $row[slno]; ?>" onClick="connect(<?php echo $row[slno]; ?>)"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</button></div>
<button class="pull-left btnhideshow show_hide" data-toggle="collapse" data-target="#demo<?php echo $row['slno']; ?>"><li class="fa fa-comments show_hide" style="margin-right: 6px;"></li>Comment</button>
<button class="pull-left btnhideshow show_hide"><li class="fa fa-share-alt show_hide" style="margin-right: 6px;"></li>Share</button>
<div class="clear"></div>
<div class="clear"></div>
</div>
<!-- Display All Comments -->
<div id="myModal<?php echo $row['slno']; ?>" class="modal">
<div id="DialogDiv<?php echo $row['slno']; ?>">
<!-- Modal content -->
<div class="modal-content" id="modalDialog<?php echo $row['slno']; ?>">
<p class="popupheading"><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?></p>
<?php
$result2 = $linkID1->query("select upc.slno,upc.Comment,upc.CommentedUserID,up.ProfilePic from user_posts_comments upc join user_picture up on upc.CommentedUserID=up.UserID where PostID='$row[slno]' order by upc.slno")
or
die(mysqli_error());
while($row2 = mysqli_fetch_array($result2))
{
?>
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row2['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row2['Comment']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<div id="nReply2<?php echo $row2['slno']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox2<?php echo $row2['slno']; ?>" onkeyup="enter_reply2(<?php echo $row2['slno']; ?>,<?php echo $CUID; ?>,<?php echo $row['slno']; ?>);">
</div>
</div>
<div class="clear"></div>
<!-- Nested Comments Starts -->
<div id="NestedCmntsDialog" class="nestedcmnts">
<?php
$result3 = $linkID1->query("select upcr.slno,upcr.PostID,upcr.ReplyTo,upcr.ReplyBy,upcr.Comments,up.ProfilePic from user_posts_comments_reply upcr join user_picture up on upcr.ReplyBy=up.UserID where upcr.PostID='$row2[slno]' and (upcr.ReplyTo='$row2[CommentedUserID]' or upcr.ReplyBy='$row2[CommentedUserID]') order by upcr.slno")
or
die(mysqli_error());
while($row3 = mysqli_fetch_array($result3))
{
?>
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row3['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row3['Comments']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<div class="clear"></div>
<div id="nReply2<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox2<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" onkeyup="enter_nested_reply2(<?php echo $row3['slno']; ?>,<?php echo $row3['ReplyBy']; ?>,<?php echo $row['slno']; ?>,<?php echo $row3['PostID']; ?>);">
</div>
</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<?php
}
?>
</div>
<!-- Nested Comments Ends -->
<?php
}
?>
<div class="invidone">Close</div>
</div>
</div>
</div>
<!-- Display All Comments -->
<div class="slidingDiv collapse" id="demo<?php echo $row['slno']; ?>">
<div class="viewallcomments">View All Comments</div>
<div class="allcomment" id="commentsLoad<?php echo $row['slno']; ?>">
<?php
$result2 = $linkID1->query("select upc.slno,upc.Comment,upc.CommentedUserID,up.ProfilePic from user_posts_comments upc join user_picture up on upc.CommentedUserID=up.UserID where upc.PostID='$row[slno]' order by upc.slno desc limit 3")
or
die(mysqli_error());
while($row2 = mysqli_fetch_array($result2))
{
?>
<!-- Showing Top 3 Comments -->
<div id="nestedReplyDiv<?php echo $row['slno']; ?>">
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row2['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row2['Comment']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<div class="clear"></div>
<div id="nReply<?php echo $row2['slno']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox<?php echo $row2['slno']; ?>" onkeyup="enter_reply(<?php echo $row2['slno']; ?>,<?php echo $CUID; ?>);">
</div>
</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<!-- Nested Comments Starts -->
<div id="NestedCmnts" class="nestedcmnts">
<?php
$result3 = $linkID1->query("select upcr.slno,upcr.PostID,upcr.ReplyTo,upcr.ReplyBy,upcr.Comments,up.ProfilePic from user_posts_comments_reply upcr join user_picture up on upcr.ReplyBy=up.UserID where upcr.PostID='$row2[slno]' and (upcr.ReplyTo='$row2[CommentedUserID]' or upcr.ReplyBy='$row2[CommentedUserID]') order by upcr.slno")
or
die(mysqli_error());
while($row3 = mysqli_fetch_array($result3))
{
?>
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row3['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row3['Comments']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<div class="clear"></div>
<div id="nReply<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" onkeyup="enter_nested_reply(<?php echo $row3['slno']; ?>,<?php echo $row3['ReplyBy']; ?>,<?php echo $row['slno']; ?>,<?php echo $row3['PostID']; ?>);">
</div>
</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<?php
}
?>
</div>
<!-- Nested Comments Ends -->
</div>
<?php
}
?>
</div>
<textarea id="commentarea<?php echo $row[slno]; ?>" class="secondtextareay pull-left" rows="2" cols="50" placeholder="Post comments here..." onkeyup="enter_comment(<?php echo $row['slno']; ?>,<?php echo $CUID; ?>);"></textarea>
<!--<div class="fileUpload second_fileupload btn btn-default pull-left">
<span><i class="fa fa-camera-retro" style="margin-right: 6px;" aria-hidden="true"></i></span>
<input type="file" class="upload" />
</div>-->
<div class="clear"></div>
</div>
</div>
<?php
}
?>
<!--post end-->
<?php
function dataLC($linkID1, $val, $CUID)
{
$UserID=$CUID;
$LgUserID=$_SESSION['uid'];
$stmt = $linkID1->prepare("select likes,comments from user_posts where slno=?");
$stmt->bind_param("s", $val);
$stmt->execute();
$stmt->bind_result($lksD,$cmntsD);
$stmt->fetch();
$stmt->close();
$GLOBALS['lks']=$lksD;
$GLOBALS['cmnts']=$cmntsD;
$stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
$stmt->bind_param("sss", $UserID,$UserID,$val);
$stmt->execute();
$stmt->bind_result($cnt);
$stmt->fetch();
$stmt->close();
if($cnt>=1)
{
$GLOBALS['disabled']="disabled";
}
else
{
$GLOBALS['disabled']="enabled";
}
$stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
$stmt->bind_param("sss", $UserID,$LgUserID,$val);
$stmt->execute();
$stmt->bind_result($cnt2);
$stmt->fetch();
$stmt->close();
if($cnt2>=1)
{
$GLOBALS['disabled']="disabled";
}
else
{
$GLOBALS['disabled']="enabled";
}
$stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
$stmt->bind_param("sss", $LgUserID,$UserID,$val);
$stmt->execute();
$stmt->bind_result($cnt3);
$stmt->fetch();
$stmt->close();
if($cnt3>=1)
{
$GLOBALS['disabled']="disabled";
}
else
{
$GLOBALS['disabled']="enabled";
}
}
?>
<script>
$('.btn').on('click', function(e)
{
$(this).prop('disabled',true); });
</script>
<script>
function UserPost() {
var x = document.getElementById('posting').value;
var timezone_offset_minutes = new Date().getTimezoneOffset();
timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
$.ajax({
type: "POST",
url: "user-post.php?p="+x+"&tz="+timezone_offset_minutes,
success: function(data) {
$("#mainsectionID").load(" #mainsectionID");
document.getElementById('posting').value='';
}
});
}
</script>
<script type="text/javascript">
function connect(num) {
$.ajax({
type: "POST",
url: "user-likes.php?id="+num,
success: function(data) {
if(data=='1')
{
$("#likescommentID"+num).load(" #likescommentID"+num);
}
}
});
}
function enter_comment(postid,userpostedid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var cmnt = document.getElementById('commentarea'+postid).value;
$.ajax({
type: "POST",
url: "user-comments.php?id="+postid+"&cmnt="+cmnt,
success: function(data2) {
if(data2=='1')
{
$("#commentsLoad"+postid).load(" #commentsLoad"+postid);
$("#likescommentID"+postid).load(" #likescommentID"+postid);
}
}
});
document.getElementById('commentarea'+postid).value='';
}
else{
//nothing
}
}
</script>
<script type="text/javascript">
function enter_reply(slno,userpostedid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var cmnt = document.getElementById('nReplyBox'+slno).value;
$.ajax({
type: "POST",
url: "user-comments-reply.php?id="+slno+"&cmnt="+cmnt,
success: function(data2) {
if(data2=='1')
{
$("#commentsLoad"+slno).load(" #commentsLoad"+slno);
}
}
});
document.getElementById('nReplyBox'+slno).value='';
}
else{
//nothing
}
}
function enter_reply2(slno,userpostedid,dno) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var cmnt = document.getElementById('nReplyBox2'+slno).value;
$.ajax({
type: "POST",
url: "user-comments-reply.php?id="+slno+"&cmnt="+cmnt,
success: function(data2) {
if(data2=='1')
{
$("#DialogDiv"+dno).load(" #DialogDiv"+dno);
//$("#modalDialog"+dno).load(" #modalDialog"+dno);
}
}
});
document.getElementById('nReplyBox2'+slno).value='';
}
else{
//nothing
}
}
</script>
<script type="text/javascript">
function enter_nested_reply(slno,userpostedid,divNo,pid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var tot=(slno*slno)+pid;
var cmnt = document.getElementById('nReplyBox'+tot).value;
$.ajax({
type: "POST",
url: "user-comments-reply-nested.php?id="+slno+"&cmnt="+cmnt+"&upid="+userpostedid,
success: function(data2) {
if(data2=='1')
{
$("#nestedReplyDiv"+divNo).load(" #nestedReplyDiv"+divNo);
}
}
});
document.getElementById('nReplyBox'+tot).value='';
}
else{
//nothing
}
}
function enter_nested_reply2(slno,userpostedid,divNo,pid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var tot=(slno*slno)+pid;
var cmnt = document.getElementById('nReplyBox2'+tot).value;
$.ajax({
type: "POST",
url: "user-comments-reply-nested.php?id="+slno+"&cmnt="+cmnt+"&upid="+userpostedid,
success: function(data2) {
if(data2=='1')
{
$("#DialogDiv"+divNo).load(" #DialogDiv"+divNo);
//$("#modalDialog"+divNo).load(" #modalDialog"+divNo);
}
}
});
document.getElementById('nReplyBox2'+tot).value='';
}
else{
//nothing
}
}
</script>
<script>
function LoadComment(num) {
var modal2 = document.getElementById('myModal'+num);
var span2 = document.getElementById("close3");
span2.onclick = function() {
modal2.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal2) {
modal2.style.display = "none";
}
}
var x = document.getElementById('myBtn2');
modal2.style.display = "block";
}
</script>
Problem resolved. Called the pagination again in the success method of ajax.
i developed a deal and coupon site and my data source is JSON. and my json file is big around 4MB. i want to show first 30 data and after scroll load next 30. so please tell me how can i do this work using JSON.
here is my code:
<?php $json = file_get_contents('offers.json');
$json_decode = json_decode($json,true);
foreach($json_decode as $data){
?>
<div class="ad-box">
<div class="ad-category"><?php echo $data['category'];?></div>
<div class="ad-image"><img class="lazy" data-src="<?php echo $data['imageUrl'];?>" src="" width="150" height="140" border="0" alt="lazy Image"/></div>
<div class="ad-title"><?php echo $data['title'] . " : " . $data['description'];?></div>
<div class="ad-url">Goto Offer</div>
</div>
<?php }
?>
your Json array is unknow but:
Main page:
<div id="loadbox">
<?php
$json = file_get_contents('offers.json');
$json_decode = json_decode($json, true);
for ($i = 0; $i < 29; $i++):
$data = $json_decode[$i];
?>
<div class="ad-box">
<div class="ad-category"><?php echo $data['category']; ?></div>
<div class="ad-image"><img class="lazy" data-src="<?php echo $data['imageUrl']; ?>" src="" width="150" height="140" border="0" alt="lazy Image"/></div>
<div class="ad-title"><?php echo $data['title'] . " : " . $data['description']; ?></div>
<div class="ad-url">Goto Offer</div>
</div>
<?php
endfor;
?>
</div>
<script type="text/javascript">
var last = 30;
function getData(lst) {
$.get("loader.php", {'last': lst}, function (data) {
$("#loadbox").append(data);
last += 30 ;
});
}
$(function () {
$(window).scroll(function () {
buffer = 40 // # of pixels from bottom of scroll to fire your function. Can be 0
if ($("html").prop('scrollHeight') - $("html").scrollTop() <= $("html").height() + buffer) {
getDate(last);
}
});
});
</script>
in the main page you load first 30 records and active ajax on scroll end.
when one loader for ajax request:
<?php
$json = file_get_contents('offers.json');
$json_decode = json_decode($json, true);
$start = (int) $_GET['last'] ;
for ($i = $start ; $i < ($start+30) ; $i++):
$data = $json_decode[$i];
?>
<div class="ad-box">
<div class="ad-category"><?php echo $data['category']; ?></div>
<div class="ad-image"><img class="lazy" data-src="<?php echo $data['imageUrl']; ?>" src="" width="150" height="140" border="0" alt="lazy Image"/></div>
<div class="ad-title"><?php echo $data['title'] . " : " . $data['description']; ?></div>
<div class="ad-url">Goto Offer</div>
</div>
<?php
endfor;
?>
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.