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?