Link to home
Create AccountLog in
JavaScript

JavaScript

--

Questions

--

Followers

Top Experts

Avatar of rafique12
rafique12

Pop Up Message Based on Location / IP Address
Hi guys,

I'm almost there!!!

I need to add a jQuery popup based on customer location for specific products in my Magento store.

I have a script but its not executing for some reason.

I would be very grateful if someone could point out what I'm doing wrong please...

Here's the code:
ip_allocation.php <--I've used 127.0.0.1 as that's my localhost and want it to detect-- This and the proceeding file is located under localhost:8888/mywebsite.com/ -->
<?php

/*
 * ip__allocation.php
 *
 */


	$MyClient=FALSE;
	if (isset($_SERVER['REMOTE_ADDR']))
	{
		include 'ip_in_range.php';
		$clientIP=$_SERVER["REMOTE_ADDR"];
		$IPAllocation = array(
			'192.168.1.0-192.168.1.255',
			'192.168.2.0-192.168.2.255'
			'127.0.0.1',			
		);

			foreach ($IPAllocation as $addressRange) {

				if (ip_in_range($clientIP, $addressRange))
				{
					$MyClient=TRUE;
					break;
				}
			}
	}
?>

Open in new window


ip_in_range.php

<?php

/*
 * ip_in_range.php - Function to determine if an IP is located in a
 *                   specific range as specified via several alternative
 *                   formats.
 *
 * Network ranges can be specified as:
 * 1. Wildcard format:     1.2.3.*
 * 2. CIDR format:         1.2.3/24  OR  1.2.3.4/255.255.255.0
 * 3. Start-End IP format: 1.2.3.0-1.2.3.255
 *
 * Return value BOOLEAN : ip_in_range($ip, $range);
 *
 * Copyright 2008: Paul Gregg <pgregg@pgregg.com>
 * 10 January 2008
 * Version: 1.2
 *
 * Source website: http://www.pgregg.com/projects/php/ip_in_range/
 * Version 1.2
 *
 * This software is Donationware - if you feel you have benefited from
 * the use of this tool then please consider a donation. The value of
 * which is entirely left up to your discretion.
 * http://www.pgregg.com/donate/
 *
 * Please do not remove this header, or source attibution from this file.
 */

// decbin32
// In order to simplify working with IP addresses (in binary) and their
// netmasks, it is easier to ensure that the binary strings are padded
// with zeros out to 32 characters - IP addresses are 32 bit numbers
Function decbin32 ($dec) {
  return str_pad(decbin($dec), 32, '0', STR_PAD_LEFT);
}

// ip_in_range
// This function takes 2 arguments, an IP address and a "range" in several
// different formats.
// Network ranges can be specified as:
// 1. Wildcard format:     1.2.3.*
// 2. CIDR format:         1.2.3/24  OR  1.2.3.4/255.255.255.0
// 3. Start-End IP format: 1.2.3.0-1.2.3.255
// The function will return true if the supplied IP is within the range.
// Note little validation is done on the range inputs - it expects you to
// use one of the above 3 formats.
Function ip_in_range($ip, $range) {
  if (strpos($range, '/') !== false) {
    // $range is in IP/NETMASK format
    list($range, $netmask) = explode('/', $range, 2);
    if (strpos($netmask, '.') !== false) {
      // $netmask is a 255.255.0.0 format
      $netmask = str_replace('*', '0', $netmask);
      $netmask_dec = ip2long($netmask);
      return ( (ip2long($ip) & $netmask_dec) == (ip2long($range) & $netmask_dec) );
    } else {
      // $netmask is a CIDR size block
      // fix the range argument
      $x = explode('.', $range);
      while(count($x)<4) $x[] = '0';
      list($a,$b,$c,$d) = $x;
      $range = sprintf("%u.%u.%u.%u", empty($a)?'0':$a, empty($b)?'0':$b,empty($c)?'0':$c,empty($d)?'0':$d);
      $range_dec = ip2long($range);
      $ip_dec = ip2long($ip);

      # Strategy 1 - Create the netmask with 'netmask' 1s and then fill it to 32 with 0s
      #$netmask_dec = bindec(str_pad('', $netmask, '1') . str_pad('', 32-$netmask, '0'));

      # Strategy 2 - Use math to create it
      $wildcard_dec = pow(2, (32-$netmask)) - 1;
      $netmask_dec = ~ $wildcard_dec;

      return (($ip_dec & $netmask_dec) == ($range_dec & $netmask_dec));
    }
  } else {
    // range might be 255.255.*.* or 1.2.3.0-1.2.3.255
    if (strpos($range, '*') !==false) { // a.b.*.* format
      // Just convert to A-B format by setting * to 0 for A and 255 for B
      $lower = str_replace('*', '0', $range);
      $upper = str_replace('*', '255', $range);
      $range = "$lower-$upper";
    }

    if (strpos($range, '-')!==false) { // A-B format
      list($lower, $upper) = explode('-', $range, 2);
      $lower_dec = (float)sprintf("%u",ip2long($lower));
      $upper_dec = (float)sprintf("%u",ip2long($upper));
      $ip_dec = (float)sprintf("%u",ip2long($ip));
      return ( ($ip_dec>=$lower_dec) && ($ip_dec<=$upper_dec) );
    }

    echo 'Range argument is not in 1.2.3.4/24 or 1.2.3.4/255.255.255.0 format';
    return false;
  }

}
?>

Open in new window


Amended my head.phtml file

<?php
// detect if client is from specific country based on IP and show popup on specific product page.
if (Mage::registry('current_product') && Mage::registry('current_product')->getId() === "169")
{
    include '/Applications/MAMP/htdocs/mywebsite.com/ip_allocation.php';
}
?>
<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    design
 * @package     base_default
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php if (Mage::registry('current_product')) : ?>
<?php if(Mage::registry('current_product')->getId() === "169"):?>
<?php if($MyClient): ?>
<meta http-equiv="Content-Type" content="<?php echo $this->getContentType() ?>" />
<title><?php echo $this->getTitle() ?></title>
<meta name="description" content="<?php echo htmlspecialchars($this->getDescription()) ?>" />
<meta name="keywords" content="<?php echo htmlspecialchars($this->getKeywords()) ?>" />
<meta name="robots" content="<?php echo htmlspecialchars($this->getRobots()) ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<link rel="stylesheet" type="text/css" href="/js/gritter/css/jquery.gritter.css" />
<script type="text/javascript" src="/js/gritter/js/jquery.gritter.min.js"></script>
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function($){
     $.gritter.add({
        // (string | mandatory) the heading of the notification
        title: '<br />Are you a customer<br />from the United Kingdom?<br />',
        // (string | mandatory) the text inside the notification
        text: '<br /><br />You can save shipping costs and order our <?php echo trim(Mage::registry('current_product')->getName())?> directly from one of our partners, click <a href="/partners?utm_source=Country&utm_medium=Partners&utm_campaign=MyCampaign"><strong>here</strong></a> for more information.<br /><br />',
        // (string | optional) the image to display on the left
        image: '/js/gritter/images/uk-flag.jpg',
        // (bool | optional) if you want it to fade out on its own or just sit there
        sticky: true
     });}
 )
//]]>
</script>
<link rel="icon" href="<?php echo $this->getFaviconFile(); ?>" type="image/x-icon" />
<link rel="shortcut icon" href="<?php echo $this->getFaviconFile(); ?>" type="image/x-icon" />
<!--[if lt IE 7]>
<script type="text/javascript">
//<![CDATA[
    var BLANK_URL = '<?php echo $this->helper('core/js')->getJsUrl('blank.html') ?>';
    var BLANK_IMG = '<?php echo $this->helper('core/js')->getJsUrl('spacer.gif') ?>';
//]]>
</script>
<![endif]-->
<?php endif ?>
<?php endif ?>
<?php endif ?>
<?php echo $this->getCssJsHtml() ?>
<?php echo $this->getChildHtml() ?>
<?php echo $this->helper('core/js')->getTranslatorScript() ?>
<?php echo $this->getIncludes() ?>

Open in new window


The script uses a jQuery library called gritter.js
 
/*
 * Gritter for jQuery
 * http://www.boedesign.com/
 *
 * Copyright (c) 2011 Jordan Boesch
 * Dual licensed under the MIT and GPL licenses.
 *
 * Date: July 9, 2011
 * Version: 1.7.1
 */
(function(b){b.gritter={};b.gritter.options={position:"",fade_in_speed:"medium",fade_out_speed:1000,time:6000};b.gritter.add=function(f){try{return a.add(f||{})}catch(d){var c="Gritter Error: "+d;(typeof(console)!="undefined"&&console.error)?console.error(c,f):alert(c)}};b.gritter.remove=function(d,c){a.removeSpecific(d,c||{})};b.gritter.removeAll=function(c){a.stop(c||{})};var a={position:"",fade_in_speed:"",fade_out_speed:"",time:"",_custom_timer:0,_item_count:0,_is_setup:0,_tpl_close:'<div class="gritter-close"></div>',_tpl_item:'<div id="gritter-item-[[number]]" class="gritter-item-wrapper [[item_class]]" style="display:none"><div class="gritter-top"></div><div class="gritter-item">[[close]][[image]]<div class="[[class_name]]"><span class="gritter-title">[[username]]</span><p>[[text]]</p></div><div style="clear:both"></div></div><div class="gritter-bottom"></div></div>',_tpl_wrap:'<div id="gritter-notice-wrapper"></div>',add:function(g){if(!g.title||!g.text){throw'You need to fill out the first 2 params: "title" and "text"'}if(!this._is_setup){this._runSetup()}var i=g.title,n=g.text,e=g.image||"",l=g.sticky||false,m=g.class_name||"",k=b.gritter.options.position,d=g.time||"";this._verifyWrapper();this._item_count++;var f=this._item_count,j=this._tpl_item;b(["before_open","after_open","before_close","after_close"]).each(function(p,q){a["_"+q+"_"+f]=(b.isFunction(g[q]))?g[q]:function(){}});this._custom_timer=0;if(d){this._custom_timer=d}var c=(e!="")?'<img src="'+e+'" class="gritter-image" />':"",h=(e!="")?"gritter-with-image":"gritter-without-image";j=this._str_replace(["[[username]]","[[text]]","[[close]]","[[image]]","[[number]]","[[class_name]]","[[item_class]]"],[i,n,this._tpl_close,c,this._item_count,h,m],j);this["_before_open_"+f]();b("#gritter-notice-wrapper").addClass(k).append(j);var o=b("#gritter-item-"+this._item_count);o.fadeIn(this.fade_in_speed,function(){a["_after_open_"+f](b(this))});if(!l){this._setFadeTimer(o,f)}b(o).bind("mouseenter mouseleave",function(p){if(p.type=="mouseenter"){if(!l){a._restoreItemIfFading(b(this),f)}}else{if(!l){a._setFadeTimer(b(this),f)}}a._hoverState(b(this),p.type)});return f},_countRemoveWrapper:function(c,d,f){d.remove();this["_after_close_"+c](d,f);if(b(".gritter-item-wrapper").length==0){b("#gritter-notice-wrapper").remove()}},_fade:function(f,c,h,d){var h=h||{},g=(typeof(h.fade)!="undefined")?h.fade:true;fade_out_speed=h.speed||this.fade_out_speed,manual_close=d;this["_before_close_"+c](f,manual_close);if(d){f.unbind("mouseenter mouseleave")}if(g){f.animate({opacity:0},fade_out_speed,function(){f.animate({height:0},300,function(){a._countRemoveWrapper(c,f,manual_close)})})}else{this._countRemoveWrapper(c,f)}},_hoverState:function(d,c){if(c=="mouseenter"){d.addClass("hover");d.find(".gritter-close").show();d.find(".gritter-close").click(function(){var e=d.attr("id").split("-")[2];a.removeSpecific(e,{},d,true)})}else{d.removeClass("hover");d.find(".gritter-close").hide()}},removeSpecific:function(c,g,f,d){if(!f){var f=b("#gritter-item-"+c)}this._fade(f,c,g||{},d)},_restoreItemIfFading:function(d,c){clearTimeout(this["_int_id_"+c]);d.stop().css({opacity:""})},_runSetup:function(){for(opt in b.gritter.options){this[opt]=b.gritter.options[opt]}this._is_setup=1},_setFadeTimer:function(f,d){var c=(this._custom_timer)?this._custom_timer:this.time;this["_int_id_"+d]=setTimeout(function(){a._fade(f,d)},c)},stop:function(e){var c=(b.isFunction(e.before_close))?e.before_close:function(){};var f=(b.isFunction(e.after_close))?e.after_close:function(){};var d=b("#gritter-notice-wrapper");c(d);d.fadeOut(function(){b(this).remove();f()})},_str_replace:function(v,e,o,n){var k=0,h=0,t="",m="",g=0,q=0,l=[].concat(v),c=[].concat(e),u=o,d=c instanceof Array,p=u instanceof Array;u=[].concat(u);if(n){this.window[n]=0}for(k=0,g=u.length;k<g;k++){if(u[k]===""){continue}for(h=0,q=l.length;h<q;h++){t=u[k]+"";m=d?(c[h]!==undefined?c[h]:""):c[0];u[k]=(t).split(l[h]).join(m);if(n&&u[k]!==t){this.window[n]+=(t.length-u[k].length)/l[h].length}}}return p?u:u[0]},_verifyWrapper:function(){if(b("#gritter-notice-wrapper").length==0){b("body").append(this._tpl_wrap)}}}})(jQuery);

Open in new window


What is supposed to happen is upon detection of the ip on a specific product  (I've used ID169)
a popup message should appear but so far DITTO!

Help will be appreciated...

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of GaryGary🇮🇪

Try placing the function at the bottom of the page, from a quick look it is appending the body but you have the code before the body is created in DOM

Avatar of rafique12rafique12

ASKER

Do you mean the footer.phtml?

Avatar of GaryGary🇮🇪

Yes.

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Cool.

Okay thanks, I've tried moving the following to the bottom of the page:

<script type="text/javascript" src="/js/gritter/js/jquery.gritter.min.js"></script>
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function($){
     $.gritter.add({
        // (string | mandatory) the heading of the notification
        title: '<br />Are you a customer<br />from the United Kingdom?<br />',
        // (string | mandatory) the text inside the notification
        text: '<br /><br />You can save shipping costs and order our <?php echo trim(Mage::registry('current_product')->getName())?> directly from one of our partners, click <a href="/partners?utm_source=Country&utm_medium=Partners&utm_campaign=MyCampaign"><strong>here</strong></a> for more information.<br /><br />',
        // (string | optional) the image to display on the left
        image: '/js/gritter/images/uk-flag.jpg',
        // (bool | optional) if you want it to fade out on its own or just sit there
        sticky: true
     });}
 )
//]]>
</script>
<?php endif ?>
<?php endif ?>
<?php endif ?>

Open in new window


Now when i click the product (ID169) i get a blank screen...

Avatar of GaryGary🇮🇪

Do you have a link to the page.
Did you clear the cache.

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Sorry I still have on the localhost so cannot send any link... Cache is disabled.

Avatar of GaryGary🇮🇪

Is error reporting enabled in index.php -  a completely empty page indicates an error.

Okay fixed the blank screen, I think my path to ip_allocation.php was incorrect... Still no popup...

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


No syntax error as such but if I try to browse to the file I get:

HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.

Here we go!

Parse error: syntax error, unexpected ''127.0.0.1'' (T_CONSTANT_ENCAPSED_STRING), expecting ')' in /Applications/MAMP/htdocs/thanedirect/ip_allocation.php on line 17

Okay fixed the error, still no message popup...!

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of GaryGary🇮🇪

Was dinner time for me.
Bit confused are you still getting a blank page, or is that the error causing the blank page.

Nice...

No blank page every thing is loading just no message?!?!?
There's no Javscript error either

Avatar of GaryGary🇮🇪

Add an alert after document.ready and after the function - see if they fire.

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


alert("NOPE);

Avatar of GaryGary🇮🇪

I've just double checked your code and cannot see a reference to the jQuery library - is it definitely there?

I have jQuery referenced in the page.xml file

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


ASKER CERTIFIED SOLUTION
Avatar of GaryGary🇮🇪

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account
JavaScript

JavaScript

--

Questions

--

Followers

Top Experts

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and in almost every mainstream web browser.