Error in Ajax request with CodeIgniter (url)

0

I have a very strange problem, if anyone can help, thank you right away.

I'm developing an application in CodeIgniter 3.1.6 with PHP 7.1 and Bootstrap 4 .

  • The home screen displays a list of students (obtained from a controller named Student, "listing" method). On this page I have a button to register new students in a modal. When I click on it, the modal is displayed correctly.

  • In the modal I have a button to save the new student in the MySQL database, which makes an Ajax request. The code is as follows:

$('#btnSalvarNovoAluno').on('click', function(){
    	$.ajax({
    		url: '<?= base_url() ?>Aluno/inserir', 
    		type: 'POST',
    		data: $('#frmNovoAluno').serialize(),
    		dataType: 'json',
    		success: function(data){
    			if(data.status)
    			{
    				alert('O aluno foi inserido corretamente!');
    			}
    		},
    		error: function(){
    			alert('Ocorreu um erro ao tentar salvar o aluno.');
    		}
    	});
    });

In my settings file I put it as "base_url":

$config['base_url'] = 'http://localhost:8080/sgicesecbd/';

When I try to save, an error is generated because the application is trying to redirect to

http://localhost:8080/sgicesecbd/Aluno/listagem/<?=%20base_url()%20?>Aluno/inserir

The strange thing is that if I put the absolute URL ( link ) in the Ajax request, it works normally.

Has anyone ever been in a similar situation? Thank you in advance!

I was able to solve the problem with the help of the following topic: link It was necessary to create this global variable containing base_url in the homepage header ...

    
asked by anonymous 19.10.2017 / 02:41

1 answer

0

Your JavaScript code is not being processed by PHP. And that's fine, it usually does not pay to have PHP process the JS, they're served more efficiently if they're static.

One possible solution is to save this path in a global JS variable, which can be declared in the HTML itself:

...
<head>
    <script>var base_url = '<?= base_url() ?>';</script>
    <script src="seuScript.js"></script>
    ...
</head>

So your JS might look like this:

$('#btnSalvarNovoAluno').on('click', function(){
    $.ajax({
        url: base_url + 'Aluno/inserir', 
        type: 'POST',
        data: $('#frmNovoAluno').serialize(),
        dataType: 'json',
        success: function(data){
            if(data.status)
            {
                alert('O aluno foi inserido corretamente!');
            }
        },
        error: function(){
            alert('Ocorreu um erro ao tentar salvar o aluno.');
        }
    });
});
    
19.10.2017 / 03:42