laravel validation during ajax request - ajax

Please somebody explain this info from Laravel docs "When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code."
What does "during an AJAX request" exactly mean here?
If I'm set like this:
User submits input from a form in the view.
The route calls the method for post in the controller
The request is validated in the controller
case 1) Request passes validation and input is stored in the DB -> Response is returned as JSON for a script that updates the view on the fly.
case 2) Request doesn't pass validation, what is returned here? I think a redirect and if not how can you check if validation has failed to return a JSON instead?
And is this scenario similar to what the docs talk about? If not then what?

The response to an AJAX call in this case is a JSON string
Case 1: as you said
Case 2: A JSON String with the error messages. Look into your Chrome dev tools into the Network tab, there you'll see the exact responses.

When handling a validation failure, laravel automatically generates an error response. Normally this will redirect the user back to their form, but in the case of an AJAX request it will instead return a JSON response with the details of what failed validation.
Laravel relies on the symfony request object to detect AJAX requests, specifically this line:
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
If you are encountering issues with your requests not being treated as AJAX, make sure your client is properly setting the X-Requested-With header

Related

How does postman app set request body for a GET request

When I was trying in browser to send a GET request with data from bootstrap datatable ajax to a C# MVC controller method, not all the data that was send was mapped to the model object. Some properties in the model object still remained with null/default value.
I verified the property names and no issues in that. But when I did the same thing in postman app the data was successfully bound to the model object.
Two things that I noted in the postman app is that:
The request data is not send in the query string parameter rather in
the request body with still the method type as GET (I don't know
how that is possible), but in browser as usual the data was URL
encoded and was sent as query string parameter.
In post man app the request headers also contains "Content-Type"
header with "application/json" as value.
So I also tried with "Content-Type" header with "application/json" but still no use the data was not bound.
Finally I chose the common way, I just set the "Content-Type" header with "application/json", stringified the data with JSON.stringify and I set the type as "POST" and it successfully got mapped.
What I got struggling is, how does the postman app alone can send a GET request like that with data in the request body.
If anyone has idea about this please tell me that would help me to have an idea about the HTTP requests.
1.) PostMan - GET Request Format
2.) PostMan - Get Request Network Data
3.) PostMan - Get Request Network Data - Raw Format
4.) Backend - Contoller Received Data
1.) Browser - GET Request Format
2.) Browser - Query String Parameters
3.) Backend - Contoller Received Data

Laravel AJAX call response is redirect to login page

I'm using AJAX. I call the server which calls an API and gets its response. I try to return the response in JSON to the client. But my Laravel has Middleware that checks token is valid. And when it's invalid, it'll redirect to login page. So the response I return is not JSON from API call but is the HTML of the redirected login page. I don't know what to do about this. One, the response is not the expected JSON and two, how do I keep the mechanism of redirecting to login page when the situation is an AJAX call and not the usual going from one page to the next.

Laravel 5.3 Returns 302 with Request Validation - Ajax Request

I am having trouble with an ajax request to a Laravel application, specifically making a POST request to an authentication controller. I'm sending a post request with SuperAgent to a controller that uses a Request class to validate the input. The request carries a password and a username. When I inspect the console I'm getting back a GET 200 OK and a POST 302 Not Found. I tried debugging the application routes but nothing seemed to work.
Turns out it was something very simple. Having used jquery for a long time to make ajax request, I overlooked a very important header. The 'Accept', 'application/json' Header. Debugging the Request validation, I noticed that Laravel's expectsJson method was returning false, so all I had to do was add said header to the SuperAgent request object.

How do I handle an MVC Cross site POST?

I have to handle Cross site POSTS from Ajax calls in an MVC project.
I have a method in my controller that is supposed to accept a POST with the view model as the POST body. My page is making an ajax call to it from Javascript. This works fine if everything is under the same domain.
IE11 sends an OPTIONS request without a POST body the first time my Ajax call is made. MVC tries to route this, fails to find my method (probably because it takes the ViewModel parameter), and returns a 404. However after the first time the call errors out, subsequent calls include the POST body and are routed successfully.
I thought I could fix this easily by including an overload of my method in my controller that takes no parameters and returns a 200 (or 204) and no message body. However this gives me "The current request for action on controller type is ambiguous between the following action methods" and lists both overloads.
What is the best way to get this to route correctly? If I got to my controller method with a null ViewModel, I could return a 200/204 and probably be okay - but I don't get there, routing sends back a 404.
Solved this. CORS requires 2 things, you need all responses to include the Access-Control-Allow-Origin header, and you need to response to OPTIONS requests (either with a 200 or 204).
My OPTIONS requests were not routing correctly, returning a 404 with the Access-Control-Allow-Origin header, which caused the error but allowed the next request to work without an OPTIONS request.
I had to handle the OPTIONS requests in my Global.asax.cs

Ajax request redirect

I am doing a Ajax request, in the response depending on some condition. I might send a 301 status code with a location(redirect) URL. But when I do that there is a ajax request to the redirect URL, but I want it to be a normal request not a ajax request.
Is there a way to do that?
it's pretty easy, you might want the server to return an url instead of performing redirection, end then use window.location to perform redirection in javascript :).
Javascript can't see the redirect response, only the final response from the URL the browser was redirected to.
Javascript can try to recognize the situation by analyzing the response content: Maybe it expects JSON but gets HTML (e.g. a login page :-) )
To do it right you'd need to modify the service to return a non-redirect response code to the Javascript which it can then handle (e.g. 401 when the session expires and the user must log in again)

Resources