A
A
axblue2016-12-28 17:58:09
Laravel
axblue, 2016-12-28 17:58:09

How to improve ajax page loading code?

Hello. The site has tags. By clicking on the tag, Ajax did the loading of elements. I did it like this:

public function showCategory(Request $request, $id)
    {
        $recipes = Tag::find($id)->recipes()->where('public', '=', 1)->get();
        $tags = Tag::with('recipes')->get();
        if ($request->ajax()) {
            return view('site.recipe_load', ['recipes' => $recipes])->render();
        }
    }

$(function() {
    $('body').on('click', '.left-menu a', function(e) {
        e.preventDefault();

        $('#load a').css('color', '#dfecf6');
        $('.preloader-wrapper').addClass('active');

        var url = $(this).attr('href');
        getRecipes(url);
        window.history.pushState("", "", url);
    });

    function getRecipes(url) {
        $.ajax({
            url :  url
        }).done(function (data) {
            $('.recipes').html(data).fadeIn();
            console.log(data);
        }).fail(function () {
            alert('Recipes could not be loaded.');
        });
    }
});

Route::get('tag/{id}','[email protected]');

<a href="{{action('[email protected]',['id'=>$tag->id])}}">#{{$tag->name}}</a>

There was a problem, when you click on the tag, a link like mysite/tag/1 is generated - the elements are displayed, but after updating the address page mysite/tag/1 , the page becomes empty, since we received only the elements. How can the code be improved to solve this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav Nagorny, 2016-12-31
@leshikgo

public function showCategory(Request $request, $id)
    {
        $recipes = Tag::find($id)->recipes()->where('public', '=', 1)->get();
        $tags = Tag::with('recipes')->get();
        if ($request->ajax()) {
            return view('site.recipe_load', ['recipes' => $recipes])->render();
        }
        return view('site.recipe_load', ['recipes' => $recipes]);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question