AJAX request for PHP (Codeigniter) does not return values

Asked

Viewed 976 times

2

I’m working on a situation I haven’t been able to resolve in over two days straight. I have an AJAX that is requesting values for a controller to popular a select with cities. The request seems to be (no debug error), but however nothing comes in the return.

Javascript:

$(function() {
    $('#selectEstado').change(function() {

    var uf = $('#selectEstado').val();

    $.ajax({
        url: "busca/carregaCidades/" + uf,
        dataType: "json",
        success: function(data){
            console.log(data);
        }
    });

    });
});

Controller:

    public function carregaCidades($uf)
    {
        $resultado = $this->busca_model->getCidades($uf);
        return json_encode($resultado);
    }

Model:

    public function getCidades($uf)
    {
        $this->db->where('uf', $uf);
        $dados = $this->db->get('tb_cidades')->result();

        return $dados;
    }

Even without any error in the console, the result of the request does not come. Thanks for the help

  • 1

    by chance, if you give a var_dump in $dados inside the model comes something? Or if you give a echo $this->db->last_query(); to return the last query, when you run it in your direct bank, by phpmyadmin for example, give right wheel and return something?

  • 1

    Thank you for your answer, Marcelo! Had managed to solve, the problem was the return in the controller... I was returning PHP json to jquery, so I should have used echo instead of Return!

  • 2

    Glad you solved your problem there, now cool is how you found the solution, answer how you solved so that future users tbm can benefit from your question.

1 answer

2

Friend a single detail you sinned was that there in the controller instead of you gives a return json_encode($resultado); you would have to make a echo json_encode($resultado); ajax will take what php 'print on screen', and not communicate directly with it, for you to give a Return it catch the value.

Controller:

public function carregaCidades($uf)
{
    $resultado = $this->busca_model->getCidades($uf);
    echo json_encode($resultado);
}

hope I’ve helped.

Browser other questions tagged

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