Javascript does not receive json Response from Laravel

Asked

Viewed 529 times

0

I’m trying to get Javascript to receive the data sent by the server and play in Alert. But it always comes Undefined. I’ve looked at many topics about it on the internet and found nothing wrong with the code. In theory it was supposed to work. Can anyone help me? Thanks

Here is the JS code:

$(document).ready(function() {

    $( "#enviar" ).click(function( event ) {
        event.preventDefault();
        var email = $('#email').val();  
        var nome = $('#nome').val();
        var telefone = $('#telefone').val();
        var msg = $('#msg').val();
        $( "#cont-form" ).html('<div class="loader" id="load"><img src="img/loader.gif"></div>');
        $.ajax({
                url : '/send',
                method : 'POST',
                data : { msge: msg, mail: email, tel: telefone, name: nome, _token: token},
                success: function(data){
                    $( "#cont-form" ).html('<div class="enviada"><h1>Mensagem enviada!</h1></div>');
                    $('.enviada').hide();
                    $('.enviada').slideDown();
                    alert(data.test);
                }
        });
    });

});

Here is the part of the controller that receives the request:

public function enviar(Request $request) {
        $msg = $request['msge'];
        $nome = $request['name'];
        $email = $request['mail'];
        $telefone = $request['tel'];
        if ($telefone == '') {
            $telefone = 'Numero não informado';
        }
        $enviar = new Emails();
        $enviar->enviarEmail($nome, $email, $telefone, $msg);

    }

And finally the class that sends the email:

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Mail;
use Illuminate\Http\Response;

class Emails extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct()
    {
        //
    }

    public function enviarEmail($nome, $email, $telefone, $msg)
    {
        $title = $nome;
        $content = $msg;
        $info = [
            'nome'  => $nome,
            'email' => $email
        ];
        Mail::send('emails.send', ['title' => $title, 'content' => $content, 'telefone' => $telefone], function ($message) use($info)
        {

            $message->from($info['email'], $info['nome']);

            $message->to('[email protected]')->subject('Mensagem do Site');

        });

        return response()->json(['test' => 'Request completed']);
    }
}
  • The return of the Response must be in the controller, just add a Return at the end of your controller this way: return $enviar; Whenever the controller gives the returns to the customer, the others will always return to the classes that called it, like: Emails are returning to Controller.

  • I already tried that before posting the question and it didn’t work...

  • I only used the 4.2 until today, there is no helper response, but possibly the same, by default the Laravel already returns arrays as json, try to return only the array(in the controller), and another thing you can see is to log only in data and see what’s in it.

  • I have. All that returns is the value of $('#email'). val();

  • Although the form data is sent correctly to the recipient’s email

  • 1

    Now that I realized that when I said to return the $send, it would return the object Email, you need to pass the return of the mailEmail to a variable, try the following: $response = $enviar->enviarEmail($nome, $email, $telefone, $msg); and the Return of $response in the Controller.

  • Got it, buddy. Thanks.

  • You are welcome, it says not to use the comment to give an answer, so I’m putting one, although I won’t be able to explain it very well, but it should be helpful if someone has a similar question.

Show 3 more comments

1 answer

1


According to the information given in the comments, it was possible to discover the cause of the problem.
The function enviarEmail class Emails is returning a response for the controller with the data it wants received by JSON.

But the controller is not giving the return of this response, because who gives the result in text to the view is the first class called by the router* (the one defined in the route file).

It would be necessary to give the return of this response as follows in controller:

return $enviar->enviarEmail($nome, $email, $telefone, $msg);

Adding the return in functionenviarEmail of the object $enviar, or forwarding to another variable (only to facilitate reading):

$response = $enviar->enviarEmail($nome, $email, $telefone, $msg);
return $response;

* Sorry any error, I have no better information/exactitude working, I did not get to see in depth how this works at the source of Laravel, is a deduction.

Browser other questions tagged

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