4

I want to retrieve data from the database when the bottom of the page is hit.

Now, what I have so far:

urls.py

urlpatterns = [
   url(r'^$', feedViews.index, name='index'),
   url(r'^load/$', feedViews.load, name='load'),
]


views.py

def index(request):
    if request.method == 'GET':
        context = {
                'entry_list': Entry.objects.filter()[:5],
            }
        return render(request,'index.html',context)
    else:
        return HttpResponse("Request method is not a GET")

def load(request):
    if request.method == 'GET':
        context = {
                'entry_list': Entry.objects.filter()[:1],
            }
        return render(request,'index.html',context)
    else:
        return HttpResponse("Request method is not a GET")


index.html

...
    <script>
$(window).on("scroll", function() {
       if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
         console.log( "TEST" );

        $.ajax(
        {
            type:"GET",
            url: "/load",
            data:{

            },


         })
       }
   });
</script>
...

Basicaly it loads 5 items at the beginning and what I try to achieve is that it loads 1 more as soon as I hit the bottom of the page. So jQuery works beacuase the console.log('Test') works and in my terminal it says

"GET /load/ HTTP/1.1" 200 484

which is fine as well.

I think I messed up the ajax somehow. I am not sure though.

As you can probably tell I am a nooby but any help is highly appreciated.

jericho
  • 269
  • 1
  • 4
  • 15
  • When we make an AJAX call then we must return one JsonResponse rather than rendering any template. – Shashank May 31 '18 at 19:30
  • @Shashank So I would have to chnage this line :return render(request,'index.html',context) ? to what exactly ? – jericho May 31 '18 at 19:36
  • 1
    Have a look at this: https://stackoverflow.com/questions/20306981/how-do-i-integrate-ajax-with-django-applications You can use either HttpResponse or JsonResponse – Shashank May 31 '18 at 19:41

2 Answers2

2

Use something like this:

import json
from django.http import JsonResponse


def index(request):
    if request.method == 'GET':
        context = {
                'entry_list': Entry.objects.filter()[:5],
            }
        return JsonResponse(json.dumps(context), safe=False)
    else:
        return JsonResponse({"err_msg": "Failed"})
Max
  • 1,634
  • 1
  • 19
  • 36
1

Try it:

import json
from django.core import serializers
from django.http import JsonResponse

def index(request):
    if request.method == 'GET' and request.is_ajax():
        # Return objects
        entry = Entry.objects.filter()[:5]
        # serializers
        entry2 = serializers.serialize('json', entry)
        # convert JSON
        entry3 = [d['fields'] for d in json.loads(entry2)]
        data = dict()
        data["entry"] = entry3
    return JsonResponse(data)
  • allright. thanks I got the json now. Is there a way to display the data in my html without refreshing? I cant find a solution for that. – jericho Jun 01 '18 at 13:11
  • Nice, first part is ok. There are several ways to modify the data without reloading the page, most of which works with Ajax. Now that you already have JSON with the data, you need to work well with JavaScript to create events that update your DOM. For example, the items you load in your action can be loaded by a `$("#").append ()` into **HTML** as soon as the action is executed. Ajax also lets you perform actions before, at completion, success and error, giving you more control over the DOM. An example below: – André Thadeu Souza Jun 01 '18 at 14:17
  • `$("#novo").on("click", function () { $.ajax({ type: 'GET', dataType: 'JSON', url: 'select_estado', beforeSend: function () { }, complete: function () { }, error: function () { }, success: function (data) { $.each(data.uf, function (key, value) { var opcoes = ""; $('#titulo_eleitor_uf').append(opcoes); }); } }); });` – André Thadeu Souza Jun 01 '18 at 14:21