Codeigniter base url didn't recognized in javascript

Viewed 13132

I have an ajax request in my CI application ,here is my cstom.js file for that purpose.

$(document).ready(function(){
    var base_url='<?php echo base_url();?>';
   $('#add-ct').click(function(){      
      $.ajax({
          url:base_url+'stockmanagement/add_category',
          data:{category:$('#category').val()},
          success:function(data){
              alert(data);
          },
          error:function(err){
              alert('error'+err);
          }
      });
   });
});  

But the base_url didn't recolonized, when i check the debug console the base_url is printed as the same as the source code like this way.

var base_url='<?php echo base_url(); ?>';

UPDATE

my javascript file is included in a view file

<?php if($page=='add-category'){ echo '<script src="'.base_url().'/assets/js/custom.js"></script>'; }?>
4 Answers

In the template, I put this :

<script>
  var base_url = "<?= base_url(); ?>";
</script>
<script src="<?= base_url('assets/js/main.js'); ?>">

And then in then main.js like this :

function logout(){
    var element = document.getElementById("lobtn");
    location.href = base_url+"user/logout";
}

It will send you to "yoursite.com/user/logout"...

Edit : The "lobtn" is an ID from your Logout Button...

Related