folcotandiono's avatar

Laravel open view using ajax

Usually if we want to open view in laravel, we can put url then enter, what if we use ajax to open view? what i get in my ajax response is the html code not the view.

0 likes
4 replies
rawilk's avatar
rawilk
Best Answer
Level 47

It's not normal to return a view with ajax. It's better practice to load the page, make the ajax request and then populate your page elements with the data returned from the ajax request.

It is possible to return a view with ajax in laravel (if you render it first and return the html string), but I wouldn't recommend it. Anytime I make an ajax request, it's to receive or post data to the server, not to receive a view.

1 like
biishmar's avatar

@folcotandiono

Controller

public function functionname() {
    // your code
    
    return view('viewname')->render();
}

Javascript

ajax({
    url: 'someurl',
    data: 'somedata'
    dataType: 'JSON',
    success: function(response) {
        $('#appendID').html(response);
    }
});
ederson's avatar

I do it this way too but i'd like to learn the proper way ....

Where do I store the html code to format the data? Keeping html code in the js file doesn't look right to me.

Please or to participate in this conversation.