1

I am working on a basic blog application with Codeigniter 3.1.8 and Bootstrap 4.

The posts have comments. Of course, there is a delete comments functionality. It operates via (jQuery) AJAX:

$('.delete-comment').on('click', function(evt) {
    evt.preventDefault();
    var baseUrl = window.location.origin;
    var deleteUrl = $(this).attr('href');
    var id = $(this).data('id');
    var commentsCount = Number($("#comments_count").text());

    if (confirm('Delete this comment?')) {
        $.ajax({
            url: baseUrl + '/dashboard/comments/delete/' + id,
            method: 'GET',
            dataType: 'html',
            success: function(deleteMsg) {
                commentsCount = commentsCount - 1;
                $('tr#' + id).fadeOut('250');
                $("#comments_count").text(commentsCount);
                $('#comment_delete_msg').text("The comment has been deleted");
                $('#comment_delete_msg').slideDown(250).delay(2000).slideUp(250);
            }
        });
    }
});

In certain conditions, there is a problem with the way I get the base URL in JavaScript: var baseUrl = window.location.origin;. It only works if the blogging platform is running in the root of the website (domain).

If instead, I have it running in https://mywebsite.com/blog I need to use:

var baseUrl = window.location.protocol + '//' + window.location.hostname + '/' + window.location.pathname.split('/')[1] + '/';

Since this is a platform intended to work in both the situations above and possibly others, I need a more "universal formula" for the variable baseUrl.

Could I "borrow" it from Codeigniter? If yes, how?

Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252

2 Answers2

0

You may add a hidden input in footer like

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

Then you may able to use it in JS like

$('.delete-comment').on('click', function(evt) {
evt.preventDefault();
var baseUrl = $('#base_url').val();
....
Rejoanul Alam
  • 5,435
  • 3
  • 39
  • 68
0

You can declare global variable in footer/header/page[view file] something like

<script>var baseUrl = '<?= base_url(); ?>';</script>

Use baseUrl anywhere you need.

Saleem
  • 1,059
  • 14
  • 27