I'm implementing a feature of a Django app where I have a form that submits a user's input making an api call that returns a JSON response that I parse and display back on the page. The query results are displayed in a list that I create by iterating through each of the objects. In each list element, I have a button that when clicked opens a modal form. This form has fields for an email recipient, a full name, and a message that the user can specify before clicking submit and sending the email. I need to append some extra data to this form once the form is submitted so it can be sent to the server side and added to the email.
I've seen posts like this which seem to be doing something similar; however, the problem is that the event handler in jquery needs to know which list element it needs to get data from meaning that it has to know the current iteration of the loop in order to get the correct information.
How should I go about implementing this?
Here is the code to make the list based on the data gotten back from the server-side:
var venues = {{venues|safe}};
var dates = {{raw_dts|safe}};
var ticket_statuses = {{ticket_statuses|safe}};
var ticket_urls = {{ticket_urls|safe}};
console.log("length of artist list" + venues.length);
var $list = $("<ul class='list-group'>");
for(var i = 0; i < venues.length; i++){
$list.append("<li class='list-group-item'>Artist: {{form_artistSelect}} Location: " + venues[i].city + ', ' + venues[i].region +' Venue: ' + venues[i].name +
"Date: " + dates[i] + "tickets status: " + ticket_statuses[i] + "<br><a href = '" + ticket_urls[i] +"'" + "> ticket link</a> "+
"{% if user.is_authenticated %}"+
"<button id ='invite'type='button' class='btn btn-info btn-lg' data-toggle='modal' data-target='#myModal' venue= " +venues[i] +" date = "+ dates[i] +
"ticket_url = "+ticket_urls[i]+" artist = {{form_artistSelect}} >Invite a friend</button> <button id = 'save' type='button' class='btn btn-" +
"primary-outline'> Save concert</button> "+
"{% endif %}"+
"</li>");
}
Here is the shell of the jquery function to append the data :
$list.appendTo($("#container"));
$("#mform").submit(function()){
$('<input />').attr('type','hidden')
.attr('')
}
EDIT:
If it's not clear, I specifically need to essentially send the data that the user enters inside of the modal form bundled up with the values of ticket_urls
, venues
, dates
in the position of each array that corresponds to the position at which the button is in the list. Each of these arrays are structured with the same data ordering as it had when the JSON was parsed on the server side. For the dates array, you have this structure var dates = ["2016-03-18T12:00:00", "2016-03-19T12:00:00", "2016-03-20T12:00:00"]
where the first date is displayed in the first list element, the second in the second list element, and so on. So for example, if the button in the second list element is clicked, I need the form data to be sent along with each of the values in the second position of each of the arrays.
I was thinking of somehow doing this in the original loop, but I don't think that is possible. How would I go about doing this?
view from views.py
def search(request):
queryform = SearchForm(request.POST or None)
modalform = ModalForm(request.POST or None)
#print "query form is valid = " + str(modalform.is_valid())
if queryform.is_valid():
form_artistSelect = urllib2.quote(queryform.cleaned_data.get("artist_select"))
form_city = urllib2.quote(queryform.cleaned_data.get("city"))
form_state = urllib2.quote(queryform.cleaned_data.get("state"))
mile_radius = urllib2.quote(queryform.cleaned_data.get("radius"))
#print "testing"
url = "http://api.bandsintown.com/artists/" + form_artistSelect + "/events/search.json?api_version=2.0&app_id=YOUR_APP_ID&location=" +form_city+","+ form_state+"&radius="+ mile_radius
data = json.load(urllib2.urlopen(url))
#url = "http://api.bandsintown.com/events/search?artists[]=" + form_artistSelect + "&location=" +form_city+","+ form_state+"&radius="+ mile_radius + "&format=json&app_id=YOUR_APP_ID"
context = {
"queryform" : queryform,
"modalform" : modalform,
"data": data
}
else:
context = {
"queryform" : queryform
}
if modalform.is_valid():
form_recipient = modalform.cleaned_data.get("rec_email")
form_message = modalform.cleaned_data.get("message")
form_recname = modalform.cleaned_data.get("rec_name")
print form_recipient
print form_message
print form_recname
concert_venue = modalform.cleaned_data.get("additionalValues[venue]")
concert_date= modalform.cleaned_data.get("additionalValues[uf_date]")
concert_url = modalform.cleaned_data.get("additionalValues[ticket_url]")
artist = modalform.cleaned_data.get("additionalValues[artist]")
print "concert venue"
print concert_venue
print "concert date"
print concert_date
print "concert_url"
print concert_url
print "artist"
print artist
return render(request,"searchform.html" , context)
model where the invite will be stored
class Invite(models.Model):
sender = models.ForeignKey(User, related_name= "invite_sender", on_delete = models.CASCADE)
#recipient = models.ForeignKey(User, related_name= "invite_recipient", on_delete = models.CASCADE)
recipient = models.EmailField()
concert = models.ForeignKey(Concert, on_delete = models.CASCADE)
artist = models.ForeignKey(Artist, on_delete = models.CASCADE)
message = models.CharField(max_length = 120, blank = True, null = True)
date_sent = models.DateTimeField(auto_now_add = True, auto_now = False)
Relevant forms from forms.py
class SearchForm(forms.Form):
artist_select = forms.CharField()
city = forms.CharField()
state = forms.CharField()
radius = forms.CharField()
class ModalForm(forms.Form):
rec_email = forms.CharField()
message = forms.CharField()
rec_name = forms.CharField()
Ajax call in template
$("#mform").submit(function(){
var c = getCookie('csrftoken');
//var data1 = $().attr("");
var extraData = [];
extraData['venue'] = $("invite").attr("venue");
extraData['artist'] = $("invite").attr("artist");
extraData['f_date'] = $("invite").attr("formatted_date");
extraData['uf_date'] = $("invite").attr("date");
extraData['ticket_url'] = $("invite").attr("ticket_url");
extraData['city'] = $("invite").attr("city");
extraData['region'] = $("invite").attr("region");
extraData['artist'] = $("invite").attr("artist");
$ajax({
context:this,
type : 'POST',
dataType: 'json',
url: '/artistsearch/',
data: {
csrfmiddlewaretoken: c,
//data_form: data1,
additionalValues: extraData
},
success: function(response){}
});
});