Ajax request error with Codeigniter (url)

Asked

Viewed 733 times

0

I have a very strange problem, in case anyone can help, I thank you in advance.

I’m developing an application on Codeigniter 3.1.6 with PHP 7.1 and Bootstrap 4.

  • The start screen presents a list of students (obtained from a controller called 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 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 in the Ajax request the absolute URL (http://localhost:8080/sgicesecbd/Student/insert), 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: https://stackoverflow.com/questions/36051588/codeigniter-base-url-didnt-recongnized-in-javascript We needed to create this global variable containing the base_url in the home page header...

  • Ever tried to change <?= base_url() ?> for <?php echo base_url(); ?> ?

  • Yes, but the problem remains the same. Thank you!

  • You carried $this->load->helper('url');

  • Yes, it is loaded in the Student controller constructor.

  • Carries it in the Autoload ... $autoload['helper'] = array('url'); in application/config/autoload.php ... Try also to give a <?php echo base_url(); ?> outside the Javascript

  • Also already being loaded in Autoload...

  • Is this code in a separate js file? Because everything indicates that it is not being processed by PHP. And it’s usually not the case to actually prosecute. I suggest you create a global JS variable in the head of your HTML, and use this variable to mount the URL of the ajax call.

  • 1

    That there bfavaretto, is in a separate JS file even. I did it this way and it worked, thank you!

  • It crossed my mind, except this:

  • I posted as an answer to get more complete. I hope it helps more people with the same problem or similar.

Show 5 more comments

1 answer

0


Your Javascript code is not being processed by PHP. And that’s good, it usually doesn’t pay to have PHP process the JS, they are served more efficiently if they’re static.

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

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

With this your JS can stay 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.');
        }
    });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.