Shehzad Ahmed
Shehzad Ahmed

Reputation: 21

how to call base_url in js file

i want to call base_url() in js file because i want to call ajax in jquery

its my php file

$.ajax({
        url: '<?php echo site_url('home/update');?>',
        data: {
        email:email 
        },
        type: "POST",
        success: function(data) {
            $('#feedback').text(data).css('color','green');
        },

        });       
         } 
        else
        {
            $('#feedback').text('insert a valid email').css('color','red');
        }

        });

but i want to call in js file but i am confused how can i fix this because we can't call tags in js file

Upvotes: 2

Views: 3234

Answers (3)

mokNathal
mokNathal

Reputation: 553

there is one more solution define

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

in your PHP file and use this in your js file.

If the code is in JS script file you can always store this value in hidden input field and access that. like:

<input type="hidden" id='base_url' value="<?php echo base_url();?>" >

And in JS file

var base_url = $('#base_url').val();

Upvotes: 2

Bipin Kareparambil
Bipin Kareparambil

Reputation: 473

<script>
    var base_url = '<?php echo base_url(); ?>';
</script>
  • Write the above code in header.php file
  • Then use 'base_url' variable in all js files you want..

    $.ajax({
    url: base_url+'home/update');?>',
    data: {
    email:email 
    },
    type: "POST",
    success: function(data) {
        $('#feedback').text(data).css('color','green');
    },
    
    });       
     } 
    else
    {
        $('#feedback').text('insert a valid email').css('color','red');
    }
    
    });
    

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

JS files do not get parsed for server-side code. If you want to provide data to a function, add it as a data attribute on the element which raises the event, then read it back in JS using $(this).data('foo');, something like this:

<button id="foo" data-action="<?php echo site_url('home/update');?>" data-email="<?php echo $email; ?>">Update</button>
$('#foo').click(function() {
    $.ajax({
        url: $(this).data('action'),
        data: { email: $(this).data('email') },
        type: "POST",
        success: function(data) {
            $('#feedback').text(data).css('color','green');
        },
    });   
});

Upvotes: 1

Related Questions