Jc John Jc John - 1 month ago 6
Javascript Question

codeigniter cannot echo site_url in separate js file

I have a code to insert a data from my database. I use ajax and i separate it with js file. When i separate a js file for my ajax. I cannot echo the

echo site_url()
from it. I already autoload the url helper. When i tried to put in below in my view, i can echo my site_url.

Here is my separate js code:

function create_clinic() {
alert("<?php echo site_url(clinic)?>");
$('#btnCreateClinic').text('Saving...');
$('#btnCreateClinic').attr('disabled',true);


$.ajax({
url : "<?php echo site_url('clinic_admin/create_clinic')?>",
type: "POST",
data: $('#frm_create_clinic').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) {
alert('Added Sucessfuly');
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error');
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
$('#btnCreateClinic').text('Save'); //change button text
$('#btnCreateClinic').attr('disabled',false); //set button enable


},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding data' + jqXHR+ textStatus +errorThrown);
$('#btnCreateClinic').text('Save');
$('#btnCreateClinic').attr('disabled',false);

}
});
}


and i got error in console with this:
403 (Forbidden) - A forbidden Access.

here is my .htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /clinic/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 /index.php
</IfModule>

Answer

Set your .htaccess like this

RewriteEngine on
RewriteCond $1 !^(index\.php|assets|image|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

And in the code

url : "<?php echo base_url();?>clinic_admin/create_clinic", # with htaccess

or

url : "<?php echo base_url();?>index.php/clinic_admin/create_clinic", # withour  htaccess

before that check create_clinic() js function is working/reaching.