Danny Brown
Danny Brown

Reputation: 304

Posted Ajax sent data doesn't seem to appear in Django Views

I'm using an AJAX call to a certain url, passing in a key/value pair of data.

$.ajax({

              url: 'http://127.0.0.1:8000/tool/page4/add_team/' + String(str) + '/',
              type: 'POST',
              dataType: 'html',
              data: { 
                      'alerts_array' : data_array,
                      //'csrfmiddlewaretoken' : document.getElementsByName('csrfmiddlewaretoken')[0].value,
                    },
              async: false,
              success: function(data){
                  $('#target').html(data);
              },
              error: function(XMLHttpRequest, textStatus, errorThrown) { 
                  alert("Status: " + textStatus); alert("Error: " + errorThrown); 
              }       
        });

This is the function within my views, it is calling:

@csrf_exempt
def displayAlerts(request, team):

t = (team, )
iterator = itertools.count()

query = "SELECT * FROM tool_alert_template WHERE team = ?"

all_alert = All_alerts.objects.all()

#a = "SELECT * FROM tool_sys_team WHERE sys_team "
new_list = []

for b in Alert_template.objects.raw(query, t):
    new_list = b.convertAlert

if not new_list: #if new_list is still undefined because Sys_team.objects.raw returns nothing,
                     #then initialize it as unknown
    new_list = ["Unknown","Unknown","Unknown"]

if request.method == 'POST':
    new_list = []
    default = ["Unknown","Unknown","Unknown"]
    temp = request.POST.get('alerts_array', default)
    #new_list = request.POST['alerts_array']
    for a in temp:
        new_list.append(a)

return render_to_response('table_alerts.html',
                {'alerts_array' : new_list, 'team_name' : team, 'iterator':iterator, 'all_array':all_alert } 
                )

To preface, when I load the page, before sending the AJAX request, I have another Ajax request (not shown) that loads the page with a table of my All_alerts and Alert_template objects. Only when the user selects an option from the table does the Ajax request above get called. Because I don't want the page to refresh when this happens, I'm calling the same function for both Ajax requests and just re-rendering that chunk of HTML. Unfortunately, within my views, it seems that when I call temp = request.POST.get('alerts_array',default) , it doesn't seem to find the alerts_array because the default keeps getting shown on the page. I could probably just do all of this on the client side but I feel like I'm really close to figuring this out. Any help is appreciated! Thanks a bunch.

Upvotes: 1

Views: 118

Answers (1)

Danny Brown
Danny Brown

Reputation: 304

Pretty bummed out. All I had to do was:

new_list = request.POST.getlist("alerts_array[]", None)

If you are passing in a list through ajax, you access that array through getlist and key[]

Upvotes: 1

Related Questions