Reputation: 21
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
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
Reputation: 473
<script>
var base_url = '<?php echo base_url(); ?>';
</script>
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
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