Laravel return json view ajax request example

in Laravel return JSON response can be sent using the json laravel method. This laravel method will instinctive set the Content-Type header to application/json. The json Based data laravel method will instinctive convert the your Custom array into relevant get json Data Format response.

Special Responses

Creating A JSON Response

return Response::json(array('name' => 'Pakainfo', 'state' => 'GJ'));

Creating A JSONP Response

return Response::json(array('name' => 'Pakainfo', 'state' => 'GJ'))->setCallback(Input::get('callback'));

php laravel return json response

return response()->json([
    'name' => 'Pakainfo',
    'state' => 'GJ'
]);

blade file:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 5/6/7- jQuery Ajax Request</title>
    <script src="jquery.js"></script>
</head>
<body>
<div class="container" id="demo_example">
</div>

<script type="text/javascript">
    $.ajax(
    {
        url: "/getUserData",
        type: 'GET',
    }).done( 
        function(data) 
        {
            $('#demo_example').html(data.html);
        }
    );
</script>
</body>
</html>

controller method:

public function getUserData()
{

    $main_head = "pakainfo.com";
    $html_view = view("ajaxView",compact('main_head'))->render();
    return response()->json(['html'=>$html_view]);

}

ajaxView.blade.php file:

<h1>{{ $main_head }}</h1>

</p>
</p>

Formatting JSON data in Laravel

PHP has a built-in method like name as a json_encode() to simply encode your arrays into JSON string formatgreat format. I can implement step by step:

Read Also:  Laravel AJAX Live Search Example

$array = array('pakainfo','infinityknow','tools');
return json_encode($array);

However, latest versions of Laravel like 5/6/7 also has a its own json() method which automatically sets relevant data Http Content-Type as well as encodes JSON data:

$array = array('pakainfo','infinityknow','tools');
return response()->json($array);

Parse JSON data in Laravel Blade

One of the problems that many Backend PHP developers face is parsing the array to JSON the JSON outputs from third-party any Rest APIs as well as print or display in Laravel Blade Views files. To do therefor, let us use the simple JSON object we make my previously post. We will used built-in json_decode() method of PHP to first step the JSON data:

Read Also:  Laravel Tips Tricks and Techniques for Developers

$readDataArr = '["pakainfo","infinityknow","tools"]';
$result_data = json_decode($readDataArr);
echo $result_data[0];

Observe the bellow example to know step by step more about JSON Response āˆ’

Phase 1 āˆ’ Include the bellow line in app/Http/routes.php file.

app/Http/routes.php

Route::get('get-data',function() {
   return response()->json(['name' => 'Magan Libasiya', 'state' => 'Rajkot']);
});

Phase 2 āˆ’ Visit the bellow URL to test the json response.

http://localhost:8000/get-data

Laravel json response from controller example

If you are working with PHP Based REST API Http Call then you always required to return json data response using response()->json($readDataArr) that method any client based js framework can handle with print it simply. We made bellow laravel controller method in this method We here data return json array data response, that method you can know step by step. laravel provide response() helper and it will help to response of json object. But if you are working on Core PHP then you have to do json_encode() before send results. In laravel source code you can do it simply like this bellow method:

Read Also:  laravel try catch error handling (exception in controller)

Example:

public function getJsonData()
{
    $readDataArr = ['id'=>98, 'name'=>'pakainfo'];
    return response()->json($readDataArr);
}

I hope you get an idea about laravel return json.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, donā€™t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1. Read Also:  Manage/Create Laravel 5/6/7 Widgets Using Blade files
  2. Read Also:  Set Cookies Get Cookies Delete Cookies with PHP
  3. Read Also:  OneSignal Push Notification PHP API
  4. Read Also:  WordPress Plugin Redirect After Activation
  5. Read Also:  Laravel Eloquent Useful Tips and Tricks
  6. Read Also:  Laravel Route Optional Parameters
  7. Read Also:  Simple DateTime range with two inputs Example
  8. Read Also:  Task Scheduling with Cron Job using Laravel 5/6/7
  9. Read Also:  Laravel 6 Set Timestamps using Eloquent Model
  10. Read Also:  CodeIgniter Create Custom Helper Example Tutorial
CLOSEX