How to get a PHP object in an ajax function

Asked

Viewed 595 times

4

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

What I wanted is that in the sucess of my ajax Jquery I capture this value to make some negotiations by javascript in my code.

I’m using the Laravel 5.2 framework.

Follow the code of 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 you question the route is working right what I can’t get is the return value.

  • What output do you print on the console ? You’ve tried accessing the route manually to see what results ?

  • The route returns fine, but when I check the return on the console is blank!!!!

1 answer

2


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

It is necessary to use the keyword return also.

So instead of doing:

echo $meuValor

You must do:

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

Or else:

return response($meuValor);

In the second case, the 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 thus the Laravelwill correctly return the headerresponse containing the content-type: application/json

  • 1

    Guy thanks for the help my very right here... I knew it was just a detail that went unnoticed... hauhsauhasu

Browser other questions tagged

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