0

I have an AJAX call and I want it to return my blade template with a query result.

My jQuery code:

$(document).on('click','.user-profile-child', function(){

    let id = $(this).parents('.user-profile-parent').attr('id');

    $.ajax({

        url: '/loadUserProfile',
        type: 'GET',
        data: {id: id},
        dataType: 'json',
        success: function(r){

            console.log(r);

        }

    })

});

My function which must execute the query and return the view with the results:

public function loadUserProfile(Request $request){

        $id = $request->input('id');

        $user = User::where('id',$id)->get()->toArray();

        $returnHTML = view('userProfile')->with('user', $user)->render();
        return response()->json(array('success' => true, 'html'=>$returnHTML));

    }

This is what I get in the console https://ibb.co/dth85Kh

I have tried writing my function like this but it doesn't redirect to my view and doesn't return anything in success.

public function loadUserProfile(Request $request){

        $id = $request->input('id');

        $user = User::where('id',$id)->get()->toArray();

        return view('userProfile',['user' => $user]);

    }
Grigory Volkov
  • 472
  • 6
  • 26
  • Did you check the debugger or console to see if you are getting any errors there. At least with your first example you are getting back the JSON. What is it actually returning because it says "This is a test" in the content. – SScotti Jul 08 '19 at 17:32
  • It returns the HTML markup of my `userProfile` blade template. But I don't know how to load it up. – Grigory Volkov Jul 08 '19 at 17:54
  • If you are getting that back in your AJAX call you should just be able to console.log(r.html), or $("#containerid").html(r.html); ? I don't know Laravel that well, but you might have to render the view without the header and footer for your case, so you might have to render just the content that you want. – SScotti Jul 08 '19 at 18:05
  • 1
    There is an example of how to render just a section here: https://stackoverflow.com/questions/15096241/laravel-how-to-render-only-one-section-of-a-template – SScotti Jul 08 '19 at 18:30

1 Answers1

0

That is not possible.

Blade view helpers compile down to php code. Php is read server side before sending the page to the browser so you can't run php code on the fly. So no.

I suggest using InnerHtml it append your data to the view with JavaScript and HTML.

paas
  • 11
  • 1