Support the ongoing development of Laravel.io →
posted 8 years ago
Configuration
Last updated 1 year ago.
0

Hello.

Normally Laravel return a JSON response for AJAX requests (but the client must specify it). To specify it from the client, just add the X-Requested-With header with the value XMLHttpRequest.

Something like this:

$.ajax
  ({
     type:"POST",
     beforeSend: function (request)
     {
         request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    },
...
...

If you want to return a JSON or plain response all the time, just catch in your own way the Exception in the Exceptions/Handler.php file.

Something like this in the render method:

if($e instanceof NotFoundHttpException)
{
     return response()->json(['message' => 'Bad address', 'code' => 400], 400);
}

You can get detailed info and step by step course about this here: RESTful API with Laravel

Or something more general here: Laravel Course, step-by-step

Hope it helps. Best wishes.

Last updated 8 years ago.
0

Thank you, very useful.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

hynese hynese Joined 28 Jul 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.