Welcome Guest, Not a member yet? Register   Sign In
Set currency based on IP address
#1

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 ?
Reply
#2

Are you getting any errors?? What's the issue here?
"The Most Important Thing In Life Is Showing Up"
"I Just Had A Bad Day"
"We'll Be Back"
"Further Beyond"
Reply




Theme © iAndrew 2016 - Forum software by © MyBB