PhoeniX5's avatar

How to format json data in laravel?

I need to get rid of json format and show only text with applied css.

Displayed data:

{"id":"<h3>...............................................<h3><br \> 
<h1>rzNC35gDNG6moR3w<h1>"}

Controller:

function requete()
{
    $id = Str::random();
    $res = '<h3>...............................................<h3>'
        ."<br \><h1>".$id.'<h1>';
    return response()->json(['id' => $res]);
}

View:

$(document).ready(function() {   
     $.ajax({
            url:"{{ route('support.requete') }}",                              
     });
});
0 likes
19 replies
DariusIII's avatar

You cannot use that kind of formatting in json. Json is data presentation format that has its own formatting. You can use JSON_PRETTY_PRINT, but that is about it.

Why would you want/need to use html formatting for json results?

DariusIII's avatar

Try it this way:

return view('Demo.requete', ['id' =>$id]);
rawilk's avatar

In your ajax function you have to json decode your result

$.ajax({
    url: '..',
    success: function (response) {
        response = JSON.parse(response);
        console.log(response);
    }
});
1 like
tykus's avatar

So the point is to fetch HTML using AJAX that you can append to the current page?

You can use the render() method on a view partial (no html, head, or body elements) to compile the HTML and return that response:

// Controller
function requete()
{
    $id = Str::random();
    
    return view('path.to.view.partial', compact('id'))->render();
}

Then in the view partial:

<!-- resources/views/path/to/view/partial.blade.php -->
<h3>...............................................</h3>
<br \>
<h1>{{ $id }}<h1>

You javascript is not receiving JSON, you are received a HTML string that you can append to the current view, to a placeholder element with id="placeholder":

$(document).ready(function() {   
    $.ajax({
        type: 'GET',
        url:"{{ route('support.requete') }}",
        success: function (response) {
            $('#placeholder').append(response);
        }
    });
});
PhoeniX5's avatar

So far this is the result :

Controller :

function requete()
    {
        $id = '.....................................................................'
            ."  ".session('id').'';
        session()->flush();
        return view('Demo.requete', compact('id'));   
    }

View :

$(document).ready(function() {   
                $.ajax({
                    type: 'GET',
                    url:"{{ route('support.requete') }}",
                    success: function (response) {
                        console.log(response.data);
                        $('#code').append(response.data);
                    }
                });
            });

The console log shows : undefined and nothing happens inside the view.

tykus's avatar

What do you see if you console.log(response)?

tykus's avatar

I specifically mentioned the render() method to return a HTML string rather than a full response:

return view('Demo.requete', compact('id'))->render();   
PhoeniX5's avatar

@TYKUS - I get the same result when i do :

return view('Demo.requete', compact('id'))->render();  
tykus's avatar

What do you mean loop then? If you see the contents of the view, then this is the HTML than you would append to the current page, right?

PhoeniX5's avatar

@TYKUS - No the page is already builded in html and css, i just need to add the random string from the controller to a span in the page and applie some css on it, but nothing keeps happening inside the view, when i console log response it shows the entire code of the view and if i do :

$('#code').append(response);

It keeps looping and showing the view many times inside the page but no random string.

tykus's avatar

Do you have a placeholder to receive the response, e.g.

<span id="code"></span>

There is nothing you have shared to indicate why there would be an infinite loop? Can you give more context? Also, these are contradictatory, which one is correct?

...nothing keep happening inside the view...

...showing the view many times inside the page.

PhoeniX5's avatar

@TYKUS - This is the view file :

<!DOCTYPE html>
<html>
    <head>
        <title>Support</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <style type="text/css">
            .box{
                width:600px;
                margin:0 auto;
                border:1px solid #ccc;
            }
        </style>
    </head>
    <body>
        <br />
        <div class="container box">
            <br />
            <!--img src={{ asset('LOGO.bmp') }}-->
            <h3 align="center">....................</h3>
            <br />
            <p align="center">................</p>    
            <br />
            <span id="code"></span>
        </div>
    </body>
</html>
        <script>
            $(document).ready(function() {   
                $.ajax({
                    type: 'GET',
                    url:"{{ route('support.requete') }}",
                    success: function (response) {
                        console.log(response.data);
                        $('#code').append(response.data);
                    }
                });
            });
        </script>

Controller :

function requete()
    {
        $id = '................................'
            ."  ".session('id').'';
        session()->flush();
        return view('Demo.requete', compact('id'))->render();   
    }

Console log:

undefined

The $id content is not being added to the view.

tykus's avatar

Are you returning the same view from the AJAX request as returns the "main" fully HTML document view template above? The view returned by the controller in response should be a partial, something completely separate from the main view.

PhoeniX5's avatar

@TYKUS - There are only two view files the first one redirect to this above view by :

window.location="/support/requete";

I need to get the $id content in the above view on loading.

tykus's avatar
tykus
Best Answer
Level 104

The solution I gave you above will absolutely work; however, you need a separate view partial to render the HTML for the AJAX request. This view partial should only contain the HTML that should be rendered into the existing view, e.g. a file called partial.blade.php inresources/views` directory:

<!-- resources/views/partial.blade.php -->
<h3>...............................................</h3>
<br \>
<h1>{{ $id }}<h1>

That's it, nothing else... no @section, no @extends etc.

You then render this as the AJAX response:

// Controller
function requete()
{
    $id = Str::random();
    
    return view('partial', compact('id'))->render();
}

Finally, the AJAX request:

$(document).ready(function() {   
    $.ajax({
        type: 'GET',
        url:"{{ route('support.requete') }}",
        success: function (response) {
            $('#code').append(response);
        }
    });
});

This will work.

Please or to participate in this conversation.