0

Today I'm trying to use jquery ajax in codeigniter. I got a problem. The ajax code was in js file which included at the bottom of view

<script scr="<?php echo base_url() ?>assets/js/ajax_main.js"></script>

And inside the ajax_main.js

$.ajax({
    type        : 'GET',
    url         : "<?php echo base_url() ?>akun_baru?selectedRow="+id_row, 
    encode      : true
})

.done(function(status) {
    alert(status)
});

When I write

alert("<?php echo base_url() ?>")

Sure it just shows <?php echo base_url() ?>

I just thinking that maybe I need to transfer the value of base_url() to be saved in javascript. But how?

Ukasha
  • 2,238
  • 3
  • 21
  • 30
  • 2
    This may help http://stackoverflow.com/questions/27420759/codeigniter-base-url-not-working-properly-for-ajax –  May 05 '17 at 02:35
  • Yes, that's it! I just need to define it on the header. Thanks. – Ukasha May 05 '17 at 02:37

2 Answers2

2

You can do like this:

<script>var base_url="<?php echo base_url() ?>";</script>
<script scr="<?php echo base_url() ?>assets/js/ajax_main.js"></script>

Then

alert(base_url)
Dao Luu
  • 36
  • 4
1
Add this javascript line in header.php on top

<script>var base_url="<?php echo base_url() ?>";</script>

and then link the javascript file

like this:

<script>var base_url="<?php echo base_url() ?>";</script>  <!-- on top -->
<script scr="<?php echo base_url() ?>/js/custom.js"></script> <!-- After link javascript file -->

And then go to custom.js file and check alert

alert(base_url);