Sakhawat Hossain
Sakhawat Hossain

Reputation: 463

django get data from api with ajax

I was trying to get some information from API using ajax. I was able to post data but I was unable to get all the data from the server. I am new in the Django environment, though i have tried some references. I was wanted to get the data from the server using the API that I provide and show those data by using ajax get call.

References that I have followed:

1.Django Ajax Jquery Call

2.https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html

3.https://www.sourcecodester.com/tutorials/python/11762/python-django-simple-crud-ajax.html

My code for get call:

         $.ajax({
            type: "GET",
            url: "/save_composition",
            dataType: "json",
            success: function(data) {
                alert(data)
            },
            error: function(xhr, textStatus) {
                   alert("error..");
            }});

Url section :

path('restore_composition/', views.restore_composition, name='restore_composition')

Views.py:

def restore_composition(request):
   data = SaveComposition.objects.all()
   return render(request, 'index.html', context={'data': data})

Upvotes: 0

Views: 1713

Answers (1)

DPS
DPS

Reputation: 1003

This is how ajax calls works in Django framework.

def ajax_method():
    return HttpResponse(200)

url to the ajax call

path('save_composition', views.ajax_method, name='ajax_method')

You need to set the `url-path' without forward-slash

Ajax call

$.ajax({
        type: "GET",
        url: "save_composition",
        dataType: "json",
        success: function(data) {
            alert(data)
        },
        error: function(xhr, textStatus) {
               alert("error..");
        }});

Upvotes: 1

Related Questions