Send a list to django within an ajax GET request Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Send a list to django within an ajax GET request without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I found a lot of posts here and outside talking about this problem but with POST request.

THIS IS THE PROBLEM: I have a list in my javascript and I need to send that list to django view as argument.

Javascript

 $.ajax({
    url: "myMethod",
    type: "GET",
    data: {"par1":par1,"par2":par2,"list":list},
    cache: false,
    success: function(d){
      // DO SOMETHING
    }
}

Python code (views.py)

def myMethod(request):
    par1 = request.GET.get('par1')
    par1 = request.GET.get('par2')
    list = request.GET.get('list') # DON'T WORK
    #OR
    list = request.GET.getlist('list') # DON'T WORK
    #OR
    list = request.GET.getlist('list[]') # DON'T WORK
    result = DO_SOMETHING(par1,par2,list)
    return result

I tried three ways that I found in other posts but none was working.

Answer

Could you join the list before posting and the split it in your django view?

Javascript

$.ajax({
    url: "myMethod",
    type: "GET",
    data: {"par1":par1,"par2":par2,"list":list.join("-and-")},
    cache: false,
    success: function(d){
      // DO SOMETHING
    }
}

Python code (views.py)

def myMethod(request):
    par1 = request.GET.get('par1')
    par1 = request.GET.get('par2')
    list = request.GET.get('list').split('-and-')

    result = DO_SOMETHING(par1,par2,list)
    return result
We are here to answer your question about Send a list to django within an ajax GET request - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji