CodeIgniter Forums
Set currency based on IP address - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Set currency based on IP address (/showthread.php?tid=63582)



Set currency based on IP address - Lykos22 - 11-16-2015

Hi, I need some help please. This is my code in MY_Controller

PHP Code:
// set default currency code if not set already in index()
if (!$this->session->userdata('currency_code')) {
    
$this->session->set_userdata('currency_code''USD');
    
$this->data['ajax_currency'] = true;
}

...

public function 
set_currency_ajax() {
            
        
$country_info file_get_contents('https://freegeoip.net/json/' $this->input->ip_address());
        
$country_info json_decode($country_infotrue);

        
$countries_in_euro = array('AT''BE''CY''DE''EE''FI''FR''GR''IE''IT''LT''LV''LU''MT''NL''PT''SK''SI''ES');

        if (
in_array($country_info['country_code'], $countries_in_euro)) {
            
$this->session->set_userdata('currency_code''EUR');
        }
        else if (
$country_info['country_code'] == 'GB') {
            
$this->session->set_userdata('currency_code''GBP');
        }
        else {
            
$this->session->set_userdata('currency_code''USD');
        }

        
$response = array(
            
'sess_currency' => strtolower($this->session->currency_code),
        );

        
// echo json_encode($response);
        
$this->output->enable_profiler(false)->set_output(json_encode($response))->_display();
        exit();
    } 

This is my view

PHP Code:
<span data-eur="€100" data-gbp="£75" data-usd="$115" class="price-span">$115</span>

...


<?
php if(isset($ajax_currency) && $ajax_currency === true): ?>
        <script type="text/javascript">
            $(document).ready(function() {
                $.post("<?php echo site_url('set_currency_ajax'); ?>", {}, function(response) {
                    alert(response.sess_currency);
                    $('.price-span').text( $(this).attr('data-' + response.sess_currency) );
                });
            });
        </script>
    <?php endif; ?>

What I'd like to do is, if there's no currency set in session already, to save the (new) currency set based on users ip location and do an ajax call to change the pricing on all span tags. How can I make this work properly ?


RE: Set currency based on IP address - Sentro - 11-17-2015

Are you getting any errors?? What's the issue here?