How to get a PHP object in an ajax function

4

I have the code below that does a check in my controller and it returns me a count of my request.

What I wanted is that in the success of my Jquery ajax I would capture this value to do some javascript conversations in my code.

I'm using the Laravel 5.2 framework.

Follow the code for my function in javascript and the function in the controller.

Controller:

public function verificaCPF($cpf){
        $cpfvalidoeexistente;
        if(BussinessRoles\SSV::validacaoCPF($cpf)){
            $cpfvalidoeexistente = Aluno::where('cpf', $cpf)->count();
        }
        else{
            $cpfvalidoeexistente = 0;
        }
        echo $cpfvalidoeexistente;
    }

Function in javascript:

$.ajax({
        type: "GET",
        url: '/validacpf/'+cpf, 
        success: function (result) {
            console.log(result);
            msg('sucesso', 'O registro foi atualizado com sucesso!', '#resposta')            
        },
        error: function () {            
            msg('atencao', 'Ocorreu um erro ao atualizar o registro!', '#resposta');
        }});

Before they question the route is working right what I can not do is get the return value.

    
asked by anonymous 18.02.2016 / 17:05

1 answer

2

In Laravel 5 , when we want to return something (Be HTML or be JSON ), we should use the function response or view .

It is necessary to use the keyword return as well.

So, instead of doing:

echo $meuValor

You should do:

 return response()->json($meuValor);

Or:

return response($meuValor);

In the second case, Laravel automatically treats the type passed to response , to decide whether to return a json or not.

It is important to use this function, because then, Laravel will correctly return header response containing content-type: application/json

    
18.02.2016 / 19:36