Reputation: 822
I have a button in my external js file that, when clicked, I want to be sent to a controller that I have. When I have the on click function in JQuery with the url set to my localhost, it works fine, but how do I set it so that it would work similar to the way the base_url works in CodeIgniter, so that it would work in any environment? I've tried using window.location.origin, or window.location.host instead of the localhost, but neither work. Any ideas?
My external JS button:
var html = '<div class="alert alert-success" role="alert"><p class="instruction_text text-center">' + completedText + '</p></div><input id="next_task" class="btn btn-lg btn-default text-center" style="margin-top: 150px; font-weight: bold;" type="button" value="' + text[lang]['continue'] + '"data-url="http://localhost:8888/oda/sample/instructions/' + task_id + '/' + lang + '/' + type + '">';
$('#final_message').append(html);
$(document).on('click', '#next_task', function(e) {
e.preventDefault();
location.href = $(this).data('url');
});
Thanks!
Upvotes: 0
Views: 942
Reputation: 950
You can leave that work to the browser. If the page is within the same domain you don't need to put it verbosely on your code, you can put something like that:
'"data-url="/oda/sample/instructions/' + task_id + '/' + lang + '/' + type + '"'
note that the /
on the beginning says that it will always get to the same place, disregard the current url.
But, if you need for some reason to write the full url window.location.origin
will not include the port part of your url, you would have to include window.location.port
too to make it work with your environment. and it's not a necessary thing to do in production.
window.location.host
should work if you put http://
and /
on your string:
'"data-url="http://' + window.location.host + '/oda/sample/instructions/' + task_id + '/' + lang + '/' + type + '"'
Upvotes: 1
Reputation: 77
You can define base_url value to the JS variable in view and include all external JS below that
Here, I am giving section of example head.php which is located at /your_root/application/views
<script>
var base_url = "<?php echo base_url(); ?>";
</script>
Upvotes: 1