Home » Laravel return json view ajax request example

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 Soft Delete Example Tutorial From Scratch

$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:  what does pairwise distinct mean?

$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:  Simple Jquery ajax request example with demo

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:  Laravel 5/6/7 create custom helper Function
  2. Read Also:  Laravel 6 Update Query using Eloquent Example
  3. Read Also:  PHP RESTful Web Services Tutorial for beginners
  4. Read Also:  failed to load resource: the server responded with a status of 404 (not found)
  5. Read Also:  Laravel dynamic breadcrumbs with links
  6. Read Also:  Laravel Fix RuntimeException (You need to specify a file path to store the seed laravel)
  7. Read Also:  Laravel Upload Import CSV Data Into MySQL Database
  8. Read Also:  Laravel eloquent join with condition
  9. Read Also:  How To Configure Supervisor For Laravel 5/6/7 Queue Jobs?
  10. Read Also:  How to Convert XML to JSON in PHP?

Leave a Comment

Your email address will not be published. Required fields are marked *