How to pick up the response object of an ajax request with Laravel?

Asked

Viewed 100 times

0

Staff I am making a fetch request to the Variable without using jquery and would like to get the return of this request, however when I give a console.log() in Sponse the console informs Undefined.

This is my requisition:

fetch(action, {
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "X-Requested-With": "XMLHttpRequest",
            "X-CSRF-Token": token
        },
        method: "post",
        credentials: "same-origin",
        body: JSON.stringify({
            email: email,
            password: password
        })
    })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(err => console.log(err))

This is my controller that returns the empty field information:

public function login(Request $request)
{
    if (in_array('', $request->only('email', 'password'))) {
        $json['message'] = "Campo vazio!";
        return response()->json($json);
    }

    var_dump($request->all());
}

The request was successful and the brouser informs the Response message:

inserir a descrição da imagem aqui

But the console.log(data) returns undefined, how can I return the object containing the message?

Taking advantage of the question, this is the best way to make this request?

Personal thank you

  • var_dump is wrong in this context the correct is return $request->all();

  • But the return of the message comes through the line: return response()->json($json);. var_dump I just put in for testing. Even if I take it out I still can’t get the Response message on the console.

  • console.log(data) if you only need the data he has the answer

No answers

Browser other questions tagged

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