Django View on Ajax call - javascript

I'm creating a catalogue page. On this page I want to allow user to filter the products.
So I created a sidebar with checkboxes and input texts.
I would like that every time the user changes the filter parameters, the catalogue is updated.
this is my code:
html for sidebar (filter):
<h3>Filtri:</h3>
<b>Marca:</b><br>
{% for marca in marche %}
<input type="checkbox" title="{{ marca.nome }}" value="{{ marca.nome }}" name="marca" class="marca" onclick="filtra()"> {{ marca.nome }} <br>
{% empty %}
<p>Nessuna Marca è ancora stata inserita.</p>
{% endfor %}
<br>
<b>Portata:</b> <br>
Maggiore di
<input type="text" title="portata" name="portata" id="portata" class="textbox-filtro" maxlength="4" onblur="filtra()"> kg
<br><br>
<b>Sollevamento:</b> <br>
Maggiore di
<input type="text" title="sollevamento" id="sollevamento" class="textbox-filtro" maxlength="4" onblur="filtra()"> mt
<br><br>
<b>Trazione:</b><br>
{% for tra in trazione %}
<input type="checkbox" title="{{ tra.trazione }}" value="{{ tra.trazione }}" id="{{ tra.trazione }}" class="trazione" onclick="filtra()"> {{ tra.trazione }} <br>
{% empty %}
<p>Nessuna Trazione è ancora stata inserita</p>
{% endfor %}
<br>
<b>Idroguida:</b><br>
{% for idro in idroguida %}
<input type="checkbox" title="{{ idro.idroguida }}" value="{{ idro.idroguida }}" id="{{ idro.idroguida }}" class="idroguida" onclick="filtra()"> {{ idro.idroguida }} <br>
{% empty %}
<p>Nessuna Idroguida è ancora stata inderita</p>
{% endfor %}
As you can see, I've 5 filter groups: Marca (brand), Portata (carrying capacity), Sollevamento (lift), Trazione (traction) and Idroguida (power steering).
Every time you edit these values, the javascript function filtra() is called... so onblur for text input and onclick for checkboxes.
Here the javascript code:
<script>
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function filtra() {
var marche_selezionate = [];
var marca_check = document.getElementsByClassName('marca');
for(var i = 0; i < marca_check.length; i++){
if(marca_check[i].checked){
marche_selezionate.push(marca_check[i].value);
}
}
marche_selezionate = marche_selezionate.join(',');
var portata_selezionata = document.getElementById('portata').value;
var sollevamento_selezionata = document.getElementById('sollevamento').value;
var trazioni_selezionate = [];
var trazione_check = document.getElementsByClassName('trazione');
for(i = 0; i < trazione_check.length; i++){
if(trazione_check[i].checked){
trazioni_selezionate.push(trazione_check[i].value);
}
}
var idroguida_selezionate = [];
var idroguida_check = document.getElementsByClassName('idroguida');
for(i = 0; i < idroguida_check.length; i++){
if(idroguida_check[i].checked){
idroguida_selezionate.push(idroguida_check[i].value);
}
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
var postUrl = "{% url 'carrellielevatori:carrellielevatori' %}";
$.ajax({
url: postUrl,
type: 'POST',
data: {'marche_selezionate': marche_selezionate},
success: function(result){
alert('success');
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
so, after setting up csrf token, in way to avoid the error "403 forbidden", I start looking and all the parameters and set up the 5 variables that I would like to pass at the view in way to filter up the catalogue.
I've also added some alert in the ajax call in way to know if it's successful or not. It is. The alert with "success" appear.
The problem is that everything stops here.
In fact, it seems nothing happens in the view.
here the code of the view:
def carrellielevatori(request):
lista_carrelli = Carrelli.objects.all()
lista_marche = Marche.objects.all()
lista_trazione = Trazione.objects.all()
lista_idroguida = Idroguida.objects.all()
footerForm = MailForm()
method = 'get'
if request.is_ajax():
method = 'ajax'
return render(request,
'carrellielevatori/carrellielevatori.html',
{
'title': 'Carrelli Elevatori - Giemme Lift s.r.l.',
'footerForm': footerForm,
'year': datetime.now().year,
'carrelli': lista_carrelli,
'marche': lista_marche,
'trazione': lista_trazione,
'idroguida': lista_idroguida,
'method':method,
})
to understand if it works, I've set up the variable method to "get" and displayed it on the page. Then in the ajax "if", I change the value to "ajax".
So it should change, right? the text remains "get" and never changes to "ajax".
This is a first try to see if it works. Once I know this work I'll proceed to filter the query that with the products. But if this does not work it's useless.
PS. Yes in the ajax call I pass just one parameters. This is to know if it works. Later I will proceed adding the other parameters in the data field.
To conclude, can you please tell me why does not enter in the in if request.is_ajax()':
Is this in not the right way, how can I filter the oringal query?
I've also tried with if request.method == 'POST', but i get the same result.

Here’s how I would do it:
#csrf_exempt
def carrellielevatori(request):
lista_carrelli = Carrelli.objects.all()
lista_marche = Marche.objects.all()
lista_trazione = Trazione.objects.all()
lista_idroguida = Idroguida.objects.all()
footerForm = MailForm()
method = 'get'
if request.is_ajax():
method = 'ajax'
return JsonResponse({
'title': 'Carrelli Elevatori - Giemme Lift s.r.l.',
'footerForm': footerForm,
'year': datetime.now().year,
'carrelli': lista_carrelli,
'marche': lista_marche,
'trazione': lista_trazione,
'idroguida': lista_idroguida,
'method':method,
})
In the JS:
function filtra() {
var marche_selezionate = [];
var marca_check = document.getElementsByClassName('marca');
for(var i = 0; i < marca_check.length; i++){
if(marca_check[i].checked){
marche_selezionate.push(marca_check[i].value);
}
}
marche_selezionate = marche_selezionate.join(',');
var portata_selezionata = document.getElementById('portata').value;
var sollevamento_selezionata = document.getElementById('sollevamento').value;
var trazioni_selezionate = [];
var trazione_check = document.getElementsByClassName('trazione');
for(i = 0; i < trazione_check.length; i++){
if(trazione_check[i].checked){
trazioni_selezionate.push(trazione_check[i].value);
}
}
var idroguida_selezionate = [];
var idroguida_check = document.getElementsByClassName('idroguida');
for(i = 0; i < idroguida_check.length; i++){
if(idroguida_check[i].checked){
idroguida_selezionate.push(idroguida_check[i].value);
}
}
var postUrl = "{% url 'carrellielevatori:carrellielevatori' %}";
$.post(postUrl, {'marche_selezionate': marche_selezionate},
function(result){
alert('success');
}).fail(function (data, status, xhr) {
alert(xhr.status);
alert(thrownError);
});
}

Related

Dependent forms in Django using AJAX

In my project I am trying to add a dependent forms solution from this answer. My template seems to accept all data correctly, but it is not displayed in the city field.
Models
class Country(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return u'%s' % (self.name)
class City(models.Model):
name = models.CharField(max_length=50)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
def __unicode__(self):
return u'%s' % (self.name)
urls
path('getdetails/', views.getdetails, name='getdetails'),
path('new-post/', views.new_post, name='new_post'),
views
from django.shortcuts import render
from django.http import JsonResponse
from django.http import HttpResponse
def new_post(request):
countries = Country.objects.all()
[...]
def getdetails(request):
#country_name = request.POST['country_name']
country_name = request.GET['cnt']
result_set = []
all_cities = []
answer = str(country_name[1:-1])
selected_country = Country.objects.get(name=answer)
print("selected country name ", selected_country)
all_cities = selected_country.city_set.all()
print(all_cities)
for city in all_cities:
print("city name", city.name)
result_set.append({'name': city.name})
return HttpResponse(JsonResponse({'result_set': result_set}))
templates
<select name="selectcountries" id="selectcountries">
{% for item in countries %}
<option val="{{ item.name }}"> {{ item.name }} </option>
{% endfor %}
</select>
<select name="selectcities" id="selectcities">
</select>
<!-- and jquery -->
<script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
<script>
$(document).ready(function() {
$('select#selectcountries').change(function() {
var optionSelected = $(this).find("option:selected");
var valueSelected = optionSelected.val();
var country_name = optionSelected.text();
data = {
'cnt': country_name
};
ajax('/getdetails', data, function(result) {
console.log(result);
$("#selectcities option").remove();
for (var i = result.length - 1; i >= 0; i--) {
$("#selectcities").append('<option>' + result[i].name + '</option>');
};
});
});
});
</script>
As you can see, my template receives AJAX responses, but doesn't match the form, and all cities are always undefinied. How do I fix my error to show the correct cities?
https://www.awesomescreenshot.com/video/2878370?key=0b43f35b4587436854d2fbe2ae317b6f (video)
The call back to ajax returns the response. You need to access the result_set yet.
ajax('/getdetails', data, function(response) {
console.log(response);
$("#selectcities option").remove();
for (var i = response.result_set.length - 1; i >= 0; i--) {
$("#selectcities").append('<option>' + response.result_set[i].name + '</option>');
};
});

Change URL and content without refreshing django

I am fetching a json response from my django response by this url /inbox/<str:username> to get a json response of all the messages in the conversation with that user.
The problem starts with the inbox page which holds the threads and chatbox on the same page like instagram which looks like this
but as it can be seen that I want the url to be like with the username. Let's say when I click on thread with dummy I want the url to be like "inbox/dummy" but in this my url is "/inbox" which will not let me initiate the socket for messaging, my views.py that renders this inbox template is
views for inbox
thread_objs= Thread.objects.by_user(user=request.user)
l=len(thread_objs)
chat_objs=[]
for i in range(l):
chat_objs.append(list(thread_objs[i].chatmessage_set.all()).pop())
chat_objs_serialized=[]
for i in range(l):
chat_objs_serialized.append(json.dumps(ChatMessageSerializer(chat_objs[i]).data))
for i in range(l):
print(chat_objs_serialized[i])
thread_objs_list=[]
for i in range(l):
thread_objs_list.append(json.dumps(ThreadSerializer(thread_objs[i]).data))
return render(request,'uno_startup/inbox.html',context={"Threads":thread_objs_list,"Messages":chat_objs_serialized})
now when I click a thread it's content should load on the right side of screen as with the javascript of inbox.html that is this page in this image.
javascript of inbox
<body>
<div class='container'>
<div class='row'>
<div class="col-md-4" id ="Threadholder">
<ul id ="Threadbox">
{% for object in threads %}
<li>{% if user != object.first %}{{ object.first }}{% else %}{{ object.second }}{% endif %}</li>
{% endfor %}
</ul>
</div>
<div class="col-md-8" id="Chatholder" >
<ul id="Chatbox">
</ul>
<form id="form" method="POST">
<input type="hidden" value="{{ user.username }}" id="myusername">
<input type="text" id="chat_message">
<input type="submit" class="btn btn-primary">
</form>
</div>
</div>
</div>
<script>
var threads={{ Threads|safe }};
var messages={{ Messages|safe }};
const l=threads.length
const threadholder=$("#Threadbox")
for(i=0;i<l;i++){
var data=JSON.parse(threads[i])
var Message=JSON.parse(messages[i])
var username =data.second.username
if (username=="{{ user.username }}"){
username=data.first.username
}
var thread=document.createElement("li")
var main=document.createElement("a")
var div=document.createElement("div")
var username_holder=document.createElement("p")
div.className="thread"
var p=document.createElement("p")
p.innerText=Message.message
username_holder.innerText=username
div.appendChild(username_holder)
div.appendChild(p)
main.appendChild(div)
thread.appendChild(main)
threadholder.append(thread)
};
function add_message(message){
message=JSON.parse(message)
const chatholder=$("#Chatbox")
console.log(message.user.username)
const chat_message= document.createElement("li")
var div= document.createElement("div")
var p = document.createElement("p")
var sender=message.user.username
var text=message.message
p.innerText=text
div.appendChild(p)
chat_message.appendChild(div)
if(sender=="{{ user.username }}"){
chat_message.className="user"
}
else{
chat_message.className="other"
}
chatholder.prepend(chat_message)
}
$(document).ready(function(){
$("li").click(function(){
$("#Chatbox").empty()
var other_user= this.children[0].children[0].children[0].innerText
fetch(`/inbox/${other_user}`).then(response => response.json())
.then(data => data.messages.reverse().forEach(add_message))
})
})
and this is the function that returns the json response
view for json response
thread=Thread.objects.get_or_new(user=request.user,other_username=username)
messages=thread[0].chatmessage_set.all()
l= len(messages)
messages_serialized=[]
for i in range(l):
messages_serialized.append(json.dumps(ChatMessageSerializer(messages[i]).data))
print(messages)
return JsonResponse({"messages":messages_serialized})
and this Chat function is called via this url /inbox/<str:username>
I want a method that can help me get the thread open without reloading, and updates the url, I have used AJAX but it didn't help as it also took to me the page where it gave me the Json Response from django, changing the original page.
The failed AJAX implementation
<script>
var threads={{ Threads|safe }};
var messages={{ Messages|safe }};
const l=threads.length
const threadholder=$("#Threadbox")
for(i=0;i<l;i++){
var data=JSON.parse(threads[i])
var Message=JSON.parse(messages[i])
var username =data.second.username
if (username=="{{ user.username }}"){
username=data.first.username
}
var thread=document.createElement("li")
var main=document.createElement("a")
var div=document.createElement("div")
var username_holder=document.createElement("p")
div.className="thread"
var p=document.createElement("p")
p.innerText=Message.message
username_holder.innerText=username
div.appendChild(username_holder)
div.appendChild(p)
main.appendChild(div)
thread.appendChild(main)
threadholder.append(thread)
};
function add_message(message){
message=JSON.parse(message)
const chatholder=$("#Chatbox")
console.log(message.user.username)
const chat_message= document.createElement("li")
var div= document.createElement("div")
var p = document.createElement("p")
var sender=message.user.username
var text=message.message
p.innerText=text
div.appendChild(p)
chat_message.appendChild(div)
if(sender=="{{ user.username }}"){
chat_message.className="user"
}
else{
chat_message.className="other"
}
chatholder.prepend(chat_message)
}
$(document).ready(function(){
$("li").click(function(){
$("#Chatbox").empty()
var other_user= this.children[0].children[0].children[0].innerText
<script>
var threads={{ Threads|safe }};
var messages={{ Messages|safe }};
const l=threads.length
const threadholder=$("#Threadbox")
for(i=0;i<l;i++){
var data=JSON.parse(threads[i])
var Message=JSON.parse(messages[i])
var username =data.second.username
if (username=="{{ user.username }}"){
username=data.first.username
}
var thread=document.createElement("li")
var main=document.createElement("a")
var div=document.createElement("div")
var username_holder=document.createElement("p")
div.className="thread"
var p=document.createElement("p")
p.innerText=Message.message
username_holder.innerText=username
div.appendChild(username_holder)
div.appendChild(p)
main.appendChild(div)
thread.appendChild(main)
threadholder.append(thread)
};
function add_message(message){
message=JSON.parse(message)
const chatholder=$("#Chatbox")
console.log(message.user.username)
const chat_message= document.createElement("li")
var div= document.createElement("div")
var p = document.createElement("p")
var sender=message.user.username
var text=message.message
p.innerText=text
div.appendChild(p)
chat_message.appendChild(div)
if(sender=="{{ user.username }}"){
chat_message.className="user"
}
else{
chat_message.className="other"
}
chatholder.prepend(chat_message)
}
$(document).ready(function(){
$("li").click(function(){
$("#Chatbox").empty()
var other_user= this.children[0].children[0].children[0].innerText
$.ajax({
type: "GET",
url: {% url 'Chat' username=other_user %},
data: {'Messages': messages}
})
.done(function(response) {
console.log(reposne)
});
})
})
})
})
Your Django view is reloading the page because it's returning a response of content type HTML instead of, say, JSON.
Instead of
return render(request,'uno_startup/inbox.html',context={"Threads":thread_objs_list,"Messages":chat_objs_serialized})
Do something like
from django.http import JsonResponse
...
return JsonResponse({"Threads": thread_objs_list, "Messages": chat_objs_serialized})
You should still fetch this response from the front-end using JavaScript/AJAX.
As for how to change the URL without inducing a page refresh, refer to this answer.

How to submit a Django form using JavaScript (jQuery)

I'm working on a web app project. I had a problem with file upload. Then I realized that my team mate changed the default submit button in create_form.html. It works like in 5. and 6. and i need to collect file data as well.
What should I add to .js files to submit and save file?
forms.py
class DocumentUpload(forms.ModelForm):
class Meta:
model = Form
fields = ('file',)
models.py
class Form(TimeStampedModel, TitleSlugDescriptionModel):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=512)
is_final = models.BooleanField(default=False)
is_public = models.BooleanField(default=False)
is_result_public = models.BooleanField(default=False)
file = models.FileField(null=True, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('form-detail', kwargs={'slug': self.slug})
views.py
def create_form(request):
if request.method == 'POST':
user = request.user
data = ParseRequest(request.POST)
print(data.questions())
print(data.form())
parsed_form = data.form()
parsed_questions = data.questions()
# tworzy formularz o podanych parametrach
formfile = DocumentUpload(request.POST, request.FILES or None)
if formfile.is_valid():
form = formfile.save(commit=False)
print(form)
form.author = user
form.title = parsed_form['title']
form.is_final = parsed_form['is_final']
form.is_result_public = parsed_form['is_result_public']
form.description = parsed_form['description']
form.save()
# zapisuje pytania z ankiety wraz z odpowienimi pytaniami
for d in parsed_questions:
question = Question(form=form, question=d['question'])
question.save()
# dla kazdego pytania zapisz wszystkie opcje odpowiadania
for opt in d['options']:
option = Option(question=question, option=opt)
option.save()
return render(request, 'forms/form_form.html', {})
else:
form = DocumentUpload()
return render(request, 'forms/form_form.html', {'form': form})
create_form.html
Here I have to submit {{ form.as_p }} <- I have to submit this input in JS**
{% block content %}
<form method="post" id="form" enctype='multipart/form-data'>
{%csrf_token %}
<div class="form-group">
{% csrf_token %}
<label for="form-title">Tytuł formularza</label>
<input id="form-title" class="form-control" type="text"
placeholder="Tytuł" required/>
</div>
{{ form.as_p }}
.... more divs ...
<input class="btn btn-default" type="submit" value="zapisz"/>
</form>
{% endblock %}
collect_data.js
This is my function called to save inputs from create_form.html instead of:
<input class="btn btn-default" type="submit" value="zapisz"/>
but I don't know how to save input from:
{{ form.as_p }}
function collect_data() {
var csrftoken = getCookie('csrftoken');
var data = {
form_title: $('#form-title').val(),
is_final: $('#form-is-final').prop('checked'),
is_public: $('#form-is-public').prop('checked'),
is_result_public: $('#form-is-result-public').prop('checked'),
description: $('#description').val(),
questions: [],
num_questions: num_questions,
csrfmiddlewaretoken: csrftoken
};
for (var k = 0; k < num_questions; k++) {
var my_data = {};
var question_k = $('#question-' + k);
my_data.question = question_k.find('#question-text').val();
my_data.answer_type = question_k.find('select').val();
my_data.options = [];
for (var j = 0; j < num_question_options[k]; j++) {
var answer = question_k.find('#answer-' + j).val();
if (answer !== '') {
my_data.options.push(answer)
}
}
my_data.num_options = my_data.options.length;
data.questions.push(my_data)
}
return data
}
submit_data_create.js
$(document).ready(function (event) {
$(document).on('submit', '#form', function (e) {
e.preventDefault();
var data = collect_data();
$.ajax({
type: 'POST',
url: '/form/create/',
data: data,
success: function (data, textStatus) {
window.location.href = '/form/list/'
},
fail: function (response) {
alert('Coś poszło nie tak.');
}
});
})
});

Why can't my post functions access a variable above it?

I'm trying to figure out why the post functions at the end of the following code do not have access to the userID variable (I'm assuming it's a scope issue as logging userId immediately before the functions returns the correct value).
$.get("/set_languages_user", function(res) {
console.log(res)
if ( res.length === 0 ) {
var getUserInfo = $.get('/set_user', function(res){
var langConfirmSource = $('#language-confirmation-template').html();
var langConfirmCompiled = Handlebars.compile(langConfirmSource);
var langConfirmTemplate = langConfirmCompiled(res)
$('body').append(langConfirmTemplate)
$('html').toggleClass('disable_scrolling')
var userId = res.id
var native_language = res.native_language
var learning_language = res.learning_language
$(document).on('submit', '#language_confirmation', function(e){
e.preventDefault()
// prevent user from continuing if they haven't checked that they agree to the term's of use
if ( $('#touCheck').is(':checked')) {
console.log('checked!!!')
// this function finds the ID of the User's defined languages
var getUserInfo = $.get('/languages.json', function(lang){
// Find the ID of the languages the User is supporting in order to submit to languages_users db
for (i = 0; i < lang.length; i++) {
if (lang[i].language === native_language) {
var confirmedUserNativeInt = lang[i].id
}
}
for (i = 0; i < lang.length; i++) {
if (lang[i].language === learning_language) {
var confirmedUserLearningInt = lang[i].id
}
}
console.log(confirmedUserNativeInt)
console.log(confirmedUserLearningInt)
console.log(userId)
// creates a new instance in languages_user for the learningLanguage (level 1)
$.post( "/languages_users", { languages_user:{ language_id: confirmedUserLearningInt, user_id: userId, level: 1 }})
// creates a new instance in languages_user for the nativelanguage (level 5)
$.post( "/languages_users", { languages_user:{ language_id: confirmedUserNativeInt, user_id: userId, level: 5 } })
$('.signon_language_confirmation').remove()
$('html').toggleClass('disable_scrolling')
});
} else {
console.log('not checked!!!')
$('.wrapper_tou_signup').append('<p class="message_form_error">You must agree to Lexody\'s Terms of Use to continue.</p>')
}
})
});
}
})
Here is the handlebars template that is being rendered:
<script id="language-confirmation-template" type="text/x-handlebars-template">
<div class="signon_language_confirmation">
<p class="title_langconf">Welcome to</p>
<img src="">
<div class="wrapper_form_dark language_confirmation_form wrapper_form_sign_on">
<form id="language_confirmation">
<div class="form_section">
<div class="wrapper_input col_16_of_16">
<p>I speak {{native_language}} <svg class="icon_standard"><use xlink:href="#{{native_language}}"/></svg></p>
<p>I am learning {{learning_language}} <svg class="icon_standard"><use xlink:href="#{{learning_language}}"/></svg></p>
<div class="wrapper_tou_signup">
<p><input type="checkbox" name="tou" value="agree" id="touCheck"> I agree to Lexody's terms of use.</p>
</div>
<div class="submit_cancel">
<input type="submit" value="Submit" class="btn_primary submit">
</div>
</div>
</div>
</form>
</div>
</div>
When I submit I'm getting "Uncaught ReferenceError: userId is not defined(…)". How do I make that variable accessible to those functions and why is that variable not accessible but the others ('confirmedUserLearningInt' and 'confirmedUserNativeInt') are?
Thanks in advance.
you have not declared the var's somewhere where the post method can reach, as you can see in your code the vars are inside a if statement which is inside a for loop, you should declare the var before the for loop like this:
$.get("/set_languages_user", function(res) {
console.log(res)
if ( res.length === 0 ) {
var getUserInfo = $.get('/set_user', function(res){
var langConfirmSource = $('#language-confirmation-template').html();
var langConfirmCompiled = Handlebars.compile(langConfirmSource);
var langConfirmTemplate = langConfirmCompiled(res)
$('body').append(langConfirmTemplate)
$('html').toggleClass('disable_scrolling')
var userId = res.id
var native_language = res.native_language
var learning_language = res.learning_language
$(document).on('submit', '#language_confirmation', function(e){
e.preventDefault()
// prevent user from continuing if they haven't checked that they agree to the term's of use
if ( $('#touCheck').is(':checked')) {
console.log('checked!!!')
// this function finds the ID of the User's defined languages
var getUserInfo = $.get('/languages.json', function(lang){
// Find the ID of the languages the User is supporting in order to submit to languages_users db
var confirmedUserNativeInt; //<<<<<<<<<<<<<<
for (i = 0; i < lang.length; i++) {
if (lang[i].language === native_language) {
confirmedUserNativeInt = lang[i].id
}
}
var confirmedUserLearningInt;//<<<<<<<<<<<<<<<<
for (i = 0; i < lang.length; i++) {
if (lang[i].language === learning_language) {
confirmedUserLearningInt = lang[i].id
}
}
console.log(confirmedUserNativeInt)
console.log(confirmedUserLearningInt)
console.log(userId)
// creates a new instance in languages_user for the learningLanguage (level 1)
$.post( "/languages_users", { languages_user:{ language_id: confirmedUserLearningInt, user_id: userId, level: 1 }})
// creates a new instance in languages_user for the nativelanguage (level 5)
$.post( "/languages_users", { languages_user:{ language_id: confirmedUserNativeInt, user_id: userId, level: 5 } })
$('.signon_language_confirmation').remove()
$('html').toggleClass('disable_scrolling')
});
} else {
console.log('not checked!!!')
$('.wrapper_tou_signup').append('<p class="message_form_error">You must agree to Lexody\'s Terms of Use to continue.</p>')
}
})
});
}
})

symfony2 ajax simple request

Im learning programming with Symfony2 and I have some problems with AJAX request, but I dont know which are the errors.
I try refresh 2 combobox
Combobox1 has one list of name of some courses
Combobox2 has to refresh according to ComboBox1 id selection
Javascript
function ListarProgramas(codfacu)
{
$('#SelProgramas').html('cargando...');
var datos = "IdFacultad="+codfacu;
$.post(Routing.generate('bibliotecaportada_listar_programas'),
{IdFacultad: codfacu},
function(data)
{
if(data.responseCode == 200 )
{
$('#SelProgramas').html(data.ProgramasHtml);
}
}, "json");
}
HTML
<select name="SelEspecie" id="SelEspecie" onchange="ListarProgramas(this.value)" style="width: 350px;text-align: center">
<option value="0">SELECCIONE FACULTAD</option>
{% for facultad in facultades %}
<option value="{{ facultad.Id }}">{{ facultad.facultad }}</option>
{% endfor %}
</select>
Controller
public function listar_programasAction()
{
$request = $this->get('request');
$IdFacultad = $request->request->get('IdFacultad');
if($IdFacultad)
{
$repository = $this->getDoctrine()->getRepository("bibliotecaportadaBundle:Programas");
$Programas = $repository->findBy(array('IdFacultad' => $IdFacultad));
$ProgramasHtml = "";
foreach ($Programas as $Programa)
{
$ProgramasHtml .= "<option>".$Programa->getProgProf()."</option>";
}
$return = array("responseCode"=>200, "ProgramasHtml" => $ProgramasHtml);
}
else
{
$return=array("responseCode"=>400, "info"=>"<option>SELECCIONE PROGRAMA</option>");
}
$return = json_encode($return);//jscon encode the array
return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
}

Categories