Sorry if this is really obvious, not great at coding and new to cookies so stil trying to get my head round it. I am trying to create a website redirect for my Magento installation. In the index.php I have placed the following code which checks the users IP location, directs them to the correct website and sets a cookie. If a cookie is already set it takes the value from the cookie and directs to a website based on this.
if ((isset($_COOKIE['penstore']) )){
$_SERVER['MAGE_RUN_CODE'] = $_COOKIE['penstore'];
$_SERVER['MAGE_RUN_TYPE'] = "website";
}
else
{
include("geoip.inc");
$ip=$_SERVER['REMOTE_ADDR'];
$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);
$country_code = geoip_country_code_by_addr($gi, "$ip");
geoip_close($gi);
switch($country_code)
{ case "CA": case "US":
$_SERVER['MAGE_RUN_CODE'] = "usa";
$_SERVER['MAGE_RUN_TYPE'] = "website";
setcookie("penstore",'usa',time()+43200);
break;
case "GB":
$_SERVER['MAGE_RUN_CODE'] = "uk";
$_SERVER['MAGE_RUN_TYPE'] = "website";
setcookie("penstore",'uk',time()+43200);
break;
default:
$_SERVER['MAGE_RUN_CODE'] = "int";
$_SERVER['MAGE_RUN_TYPE'] = "website";
setcookie("penstore",'int',time()+43200);
}
}
This all appears to work okay, my problem is finding a way to allow customers to change websites by clicking an image in the header. I have tried several different methods based on code found on the web and this site but I can't get any of it to work. I currently have the following code in my header.phtml:
<script language="text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
location.reload();
}
</script>
<img src="http://mysite.com/images/INT.gif">
<img src="http://mysite.com/images/US.gif">
<img src="http://mysite.com/images/GB.gif">
The idea is that the customer clicks on the image which causes the cookie value to be updated and the current page to be reloaded, which based on the code in the index.php, would cause a different website to load. All that happens is the # gets added to the url?
Edit: To clarify, I'm trying to switch websites, not stores, so can't use Magento store switcher.
Related
I’m working on a WordPress site requirement to redirect a user when they’re in a certain country to their country specific homepage.
(I’ve had to do this via WP Ajax because full page caching prevents it working directly on live hosting environment - I was previously doing it quite simply in functions.php hooked into 'init').
This works when I call it at the start of the header template, but only after the current page content is shown. It would be great if I could hook it in to happen before the page is displayed e.g. like using hooks such as: 'wp_loaded', ‘template_redirect’ but jQuery needs to be available...
Here is my code. It needs tidying some more but appreciate any suggestions as how to make a redirect happen before page contents displayed?
function invoke_county_redirection() {
ob_start();
?>
<script type="text/javascript">
var ajax_url = "<?= admin_url( 'admin-ajax.php' ); ?>";
jQuery.post(ajax_url, {
'action': 'country_redirection',
}, function (response) {
// Set the cookie to say we're performing the redirect - this will flag it not to happen again
createCookie('redirected', 'true');
if (response != '') {
window.location.replace(response);
}
function createCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
</script>
<?php
echo ob_get_clean();
return;
}
function country_redirection() {
$redirect_url = '';
if ( $_COOKIE['redirected'] !== 'true' ) {
/* declare empty result url */
$result['url'] = '';
/* Call on geoip plugin to get the country from their IP address */
$userInfo = geoip_detect2_get_info_from_current_ip();
$country_code = $userInfo->country->isoCode;
/* if we've retreived the country code for the current user */
if ( $country_code ) {
/* GET THE CORRECT REDIRECT URL IF APPLICABLE TO THE USER COUNTRY */
$redirect_url = get_country_url($country_code);
}
}
echo $redirect_url;
wp_die();
}
add_action( 'wp_ajax_nopriv_country_redirection', 'country_redirection' );
add_action( 'wp_ajax_country_redirection', 'country_redirection' );
Quick update in case anyone else can be helped by this.
I hooked the hooked the function invoke_county_redirection() into the wp_head hook as follows...
add_action('wp_head', "invoke_county_redirection");
This means that jQuery would be loaded and the country detect/redirect process runs.
However, it doesn't make the request syncronous and in this particular scenario with wanting to redirect before the page loads, I have given up on this. There is a minefield of issues trying to get around full page caching trying to store a cookie and do a redirect before the page loads. I should have just insisted that caching remained off where this needs to run, so this is our conclusion. We are instead optimsing the site as best we can with GTMetrix and loader.io and we will cross the bridge of scalability as and when we need to.
I am having problem with Disqus + laravel pagination. I have a post model where a post have minipost and for each post i want it to contain 5 minipost.. when I navigate to the 2nd pagination page the Disqus Discussion got auto generated for the 2nd page.. How can I avoid this duplication?
<div id="disqus_thread"></div>
<script>
var disqus_config = function () {
this.page.url = route('home');
this.page.identifier = $slug; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//testblog.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
The query
$posts = Post::where('slug', $slug)->firstOrFail()->minipost()->orderBy('created_at', 'desc')->paginate(5);
You can't achieve it directly
Because disqus will provide the comment content according to your url.
During the pagination, probably your url will change and you can't stop it.
At the same time as you wanted to show only the same disqus content throughout all the pages in url.
You should do some tricky way to do it.
Way 1 :
Have the Pagination and all the content in iframe, So that the url won't change
Way 2 :
Use Jquery Datatables or some other plugins related to it, and customize it a bit better to have your desired look
Way 3 :
Explore the disqus code and hardcode the url for that particular page
Like
this.page.url = "http://someurl.com/#!" + id;
Hope this helps you
I am using magento add to wishlist via ajax
it's working fine but after install SSL on server and make secure magento checkout pages from admin.
It give me not any response from ajax (302 Found).
But if i open this url in new tab then it's working fine.
When i use https in request url then it gives me the following html response "Reload the page to get source for: REQUEST URL" and without https there is no response to display.
here below the code which i used for :-
function additemtowishlist(wId,pId)
{
var wishlisturl = 'wishlist/index/ajaxadd/product/'+pId;
var wishlistparam = '/?wishlist_id='+wId;
var url = '<?php echo Mage::getUrl("",array('_secure'=>false))?>'+wishlisturl+wishlistparam;
new Ajax.Request(url, {
dataType: "json",
onSuccess: function(response){
if (typeof(response.responseText) == 'string') eval('data = ' + response.responseText);
if (typeof data.product_id != 'undefined') {
var htmltoshow = '<div class="messages successmessage"><div class="success-msg"><span>'+data.message+'</div></div>';
jQuery("#wishlistresulthome-"+data.product_id).html(htmltoshow);
jQuery("#customwishlist-"+data.product_id).css('visibility','hidden');
}
else {
alert(Translator.translate('Error happened while creating wishlist. Please try again later'));
}
}
});
}
Thanks in advance.
Hello Simranjeet you may try this :-
function additemtowishlist(wId,pId)
{
var wishlisturl = 'wishlist/index/ajaxadd/product/'+pId;
var wishlistparam = '/?wishlist_id='+wId;
var url = '<?php echo Mage::getUrl("",array('_secure'=>false))?>wishlist/index/ajaxadd/product/';
new Ajax.Request(url, {
method: 'post',
parameters: {'wishlist_id':wId,'product_id':pId },
onSuccess: function(response){
if (typeof(response.responseText) == 'string') eval('data = ' + response.responseText);
if (typeof data.product_id != 'undefined') {
var htmltoshow = '<div class="messages successmessage"><div class="success-msg"><span>'+data.message+'</div></div>';
jQuery("#wishlistresulthome-"+data.product_id).html(htmltoshow);
jQuery("#customwishlist-"+data.product_id).css('visibility','hidden');
}
else {
alert(Translator.translate('Error happened while creating wishlist. Please try again later'));
}
}
});
}
I discovered that ajaxToCart has ssl functionality built into it, but if the theme developer was lazy they may have neglected to include the code that tells ajaxToCart that ssl is enabled. I found it in the following code from ajax_cart_super.js.
function ajaxToCart(url,data,mine) {
var using_ssl = $jq('.using_ssl').attr('value');
if(using_ssl==1) {
url = url.replace("http://", "https://");
}
..
..
}
As you can see, ajaxToCart will replace the http with https, but only if there is an element with the class using_ssl and value=1. The developer who made my theme didn't include that element, so when the ajax request points to an unsecure page that should be secure, the ajax response won't work in jquery.
So for me, the quick fix was to just add this element onto my pages. I know this site will always have ssl enabled so I simply hard coded it into my template as shown below.
<input type="hidden" class="using_ssl" value="1" />
Once that was there, the javascript picked up the value and did the replacement. So now it works fine for me by just adding that into the template. If you are a theme developer and you want users to be able to switch this on and off, you may want to check against the settings in the admin. Although you may be on an insecure page, it will tell you if ssl is enabled in the backend, which would require this fix to be added.
I haven't tested the following but I think it would look something like this...
if(Mage::app()->getStore()->isCurrentlySecure()){
echo '<input type="hidden" class="using_ssl" value="1" />';
}
BTW, after years of appreciating stackoverflow solutions, I am making my first post here. Thanks to all contributors, the help is great and I'll try to pay it back now. :)
Try update your javascript url variable, by setting _secure to true value.
please try with below with your wishlist url just change instead of my custom action
Mage::getUrl('',array('_secure'=>true))
I think that gets you the base secure url, I believe.
Mage::getUrl('customer/account/login',array('_secure'=>true))
Will get you to the login page. In other words,
Mage::getUrl('module/controller/action',array('_secure'=>true))
How to logout from all pages of view, when I click on logout link I just from only one page when I am trying to logout from another page its not work.
My controller code is:
public function do_login()
{
$this->user = $this->input->post('user_email',TRUE);
$this->pass = $this->input->post('user_pass',TRUE);
$this->pass=md5(sha1(sha1($this->pass)));
$u = new User();
$login_data = array('email' => $this->user, 'password' => $this->pass);
$u->where($login_data)->get();
if(!empty($u->id) && $u->id > 0 )
{
$_SESSION['user_id'] = $u->id;
$_SESSION['user_name']= $u->username;
$_SESSION['fullname']= $u->fullname;
$_SESSION['is_verefied'] = $u->active;
$_SESSION['user_email']= $u->email;
$u->lastlogin = time();
$u->save();
setcookie("logged", 1, time()+86400);
if(empty($_POST['referer']))
{
if(empty($_GET['referer']))
{
$url = "./";
}
else
{
$url = $_GET['referer'];
}
}
else
{
$url = $_POST['referer'];
}
redirect($url);
}
else
{
$this->template->set_layout('inner');
$this->template->build('login_view',$this->data);
}
}
public function logout()
{
setcookie("logged", 0, time()+86400);
$_COOKIE["logged"] = '';
$_SESSION['user_id'] = '';
$_SESSION['user_name']= '';
$_SESSION['fullname']= '';
$_SESSION['is_verefied'] = '';
$_SESSION['user_email']= '';
redirect('./home/index/logout');
}
When I logout from site, and click back from browser the user information session its not deleted.
The back button of your browser might get you to cached version of you page, cached from back when you were logged it. Also, I suggest you use CodeIgniter's sessions.
To make sure you're doing everything right.
Destroy the session:
$this->session->sess_destroy();
Clear the cookie, make sure you use the same domain as when you set it up, and that the time is set to past:
setcookie('logged', '', time()-3600); // minus one hour
This script will log the user out of all pages that have a session started on them. You know a page uses sessions if this code is at the top of the code for that page:
<?php session_start(); ?>
Logging out of a website is simply clearing any session data and then destroying it.
Try the following in your logout.php:
<?php
session_start();
// what were doing here is checking for any cookies used by the session.
//If there are any, we are going to delete the data with it.
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
//now lets unset the session and destroy it
session_unset();
session_destroy();
// for the redirect, we simple use the php header to send the redirect url to the browser
header("Location: login");
Make sure when using the header function that there is no output, caused by blank spaces or html. As a logout page, there should be no output anyways since navigating to the logout page should log the user out and immediately redirect.
I use this script on all my sites and it works great. Anywhere I want the logout link to appear, I just link to the page as such:
Logout
Just make a file called logout.php and put this code into it.
Hope this helps you!
I'm looking to set up a Google Analytics Goal for newsletter subscriptions on a Magento (1.7) website. The form is pointing to 'newsletter/subscriber/new/'. A) will this url work as a Goal URL in Google Analytics? B) where can I find this folder in the Magento structure?
I'm wondering whether I can check whether GA code has been added to whatever page in this newsletter/subscriber/new/ folder it's pointing to so it will be tracked?
Take a look # _trackPageview(opt_pageURL)
Then in your newsletter template you could do something like this
<script type="text/javascript">
//<![CDATA[
var newsletterSubscriberFormDetail = new VarienForm('newsletter-validate-detail');
newsletterSubscriberFormDetail.submit = function(button, url) {
if (this.validator.validate()) {
_gaq.push(['_trackPageview', '/newsletter/subscriber/successful']);
var form = this.form;
var oldUrl = form.action;
if (url) {
form.action = url;
}
var e = null;
try {
this.form.submit();
} catch (e) {
}
this.form.action = oldUrl;
if (e) {
throw e;
}
}
}.bind(newsletterSubscriberFormDetail);
//]]>
</script>
Then create you goal url as '/newsletter/subscriber/successful';
You could also just add this line to the button onclick/submit event but it wouldn't be accurate because it before the data is validated
_gaq.push(['_trackPageview', '/newsletter/subscriber/successful']);
The answer for B is, that there is no specific folder for this:
the URL newsletter/subscriber/new/ references to the method newAction(), which you can find by examining the URL: the first element newsletter refers to the newsletter modul (Mage/Newsletter), the second element subscriber refers to the controller in this modul Mage/Newsletter/controllers/SubscriberController.php), third element refers to the action newAction() in this controller.
Inside the newAction() method is a redirect defined: $this->_redirectReferer();
This method _redirectReferer() is inherited from the class Mage_Core_Controller_Varien_Action:
protected function _redirectReferer($defaultUrl=null)
{
$refererUrl = $this->_getRefererUrl();
if (empty($refererUrl)) {
$refererUrl = empty($defaultUrl) ? Mage::getBaseUrl() : $defaultUrl;
}
$this->getResponse()->setRedirect($refererUrl);
return $this;
}
So, by subscribing to the newsletter, the method newAction() gets called, which in the end redirects to the page given in the referer, it is the same page you started the subscription. Given a basic Magento Installation, the frontend template for the newsletter subscription block is app/design/frontend/base/default/newsletter/subscription.phtml.
I don't know how Google Analytic Goals are set up, but this might help you as a starting point.