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.

List of all Google Adsense, VueJS, AngularJS, PHP, Laravel Examples.

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:

$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:

$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:

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.   global variable for all controller and views in Laravel
  2.   Clear Caches Laravel 5.7 using command line
  3.   Laravel 6 Inner Join Query Example - MySQL
  4.   PHP Laravel Get current User Information
  5.   Laravel 6 Check if a File exists before create directory
  6.   get hours/months time difference between two dates in Laravel
  7.   Extract XML Response in PHP Example
  8.   MySQL SELECT all records from today using Laravel 6
  9.   PHP Laravel Dynamically Add Active Navigation Class Example
  10.   how to upload multiple images in codeigniter?