faza faza - 9 days ago 8
Ajax Question

error 403 url ajax direct controller code igniter 3

I have error

http://localhost/psb/<?php echo site_url("Welcome/pendaftaran"); ?>
403 (Forbidden)
I'm try post data from
user.js
to controller using url:
site_url


structure
project/

----asset/

---------js/

--------------user.js

----application

---------controller/

--------------Welcome.php

user.js

function daftar()
{
var url= "<?php echo site_url('Welcome/pendaftaran')?>";
$.ajax({
url : url,
type: "POST",
data: $('#pendaftaran').serialize(),
dataType: "JSON",
}


controller welcome

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {
public function pendaftaran(){
$this->validate();
}
}


how to fix this error?

Answer

In js page not supported <?php and ?> php tag.

So, your site_url put your page header like

<script>
   var site_url = "<?php echo site_url(); ?>";
</script>

And then in user.js call var site_url variable :

function daftar() {
    $.ajax({
        context: this,
        url: site_url+"Welcome/pendaftaran",
        type: 'POST',
        dataType: 'JSON',
        data: $('#pendaftaran').serialize()
    }).done(function (data) {
        console.log(data);
    }).fail(function (data) {
        console.log('failed');
    });
}