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?

3
  • Set correct route, also, I'm not using base_url during building url option for AJAX request. It's useless part. Commented Nov 19, 2019 at 21:25
  • 1
    what's wrong with baseUrl = '<?php echo base_url();?>'? Commented Nov 19, 2019 at 21:34
  • @Vickel 's comment is, actually, the only logical way to go Commented Nov 19, 2019 at 22:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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();
....

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.