How can I update an already rendered built finished Chart.js page Flask? - javascript

How can I update an already rendered built finished Chart.js page Flask?
There is already ready Chart.js on the template page.
The value data for which is taken from Flask.
After what action on the page the values in the Flask code changed.
How can I make it so that after a certain action in the route, Flask is additionally updated Chart.js?
I have been thinking for a long time how to make it so that it is updated Chart.js when I change the values in the Flask route ("/range") - I can transfer them (changed DataFrame values) to the database - but then I don't know how to update Chart.js.
it's html code
<div class="row">
<div class="col-md-3">
<input type="text" name="From" id="From" class="form-control" placeholder="From Date"/>
</div>
<div class="col-md-3">
<input type="text" name="to" id="to" class="form-control" placeholder="To Date"/>
</div>
<div class="col-md-6">
<input type="button" name="range" id="range" value="Range" class="btn btn-success"/>
</div>
</div>
<div id="purchase_order"></div>
<hr>
<div class="row" style="align-content: center">
{# <div class="col col-lg-0"></div>#}
</div>
<div class="outer-wrapper" style="align-content: center">
<div class="table-wrapper" id="table-wrapper" style="align-content: center">
<table>
<thead>
{% for col in column_names %}
<th>{{col}}</th>
{% endfor %}
</thead>
<tbody>
{% for row in row_data %}
<tr>
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{# <div class="col col-lg-0"></div>#}
</div>
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-10">
<div>
<canvas id="myChart" width="800px" style="align-content: center"></canvas>
</div>
</div>
<div class="col-md-1">
</div>
</div>
<br>
</div>
It's script
</script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).ready(function (){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function (){
$("#From").datepicker();
$("#to").datepicker();
});
$('#range').click(function (){
var From = $('#From').val();
var to = $('#to').val();
if (From != '' && to != '')
{
$.ajax({
url:"/range",
method:"POST",
data:{From:From, to:to},
success:function (data)
{
$('#table-wrapper').html(data);
$('#table-wrapper').append(data.htmlresponse);
}
});
}
else
{
alert("Please Select the Date")
}
});
});
</script>
<script>
const labels = [{% for item in os_x %}
"{{ item }}",
{% endfor %}];
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [{% for item in os_y %}
{{ item }},
{% endfor %}],
}]
};
const config = {
type: 'line',
data: data,
options: {}
};
</script>
<script>
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
it's Flask routes
#app.route('/', methods=['GET','POST'])
#app.route('/index')
def home_page(): # put application's code here
df = pd.read_sql('select * from kotel', con=db.engine)
df['date'] = df['date'].dt.round('2min')
y_data = df['tnv'].tolist()
x_data = df['date'].tolist()
df_graph = df.copy()
return render_template('index new.html', column_names=df.columns.values, row_data=list(df.values.tolist()), column_names_graph=df_graph.columns.values, os_y = y_data, os_x = x_data)
#app.route("/range", methods=["POST","GET"])
def range():
if request.method == 'POST':
From = request.form['From']
to = request.form['to']
df = pd.read_sql('select * from kotel', con=db.engine)
df['date'] = pd.to_datetime(df['date'])
df = df.loc[(df['date'] >= From) & (df['date'] <= to)]
df['date'] = df['date'].dt.round('2min')
return jsonify({'htmlresponse': render_template('response.html', column_names=df.columns.values, row_data=list(df.values.tolist()))})

If the page is already loaded, only the values sent with the first request are displayed. If you want to see constantly updated values in your chart, you should use Websockets.
I've never worked with charts.js before, but I've used Flot Plot with Flask and Websocket to stream values to a chart in real time. it works great.
You can read more about Websockets and Flask here
If you want to load new values after and action, as example a click over a button, then you have to use ajax.
i found this page that could help you.

I see you are already using ajax. I would recommend just wrapping your code in a SetInterval() which will execute the code over and over again in a specific interval, you could do it like this
<script>
$(document).ready(function (){
setInterval(function() {
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function (){
$("#From").datepicker();
$("#to").datepicker();
});
$('#range').click(function (){
var From = $('#From').val();
var to = $('#to').val();
if (From != '' && to != '')
{
$.ajax({
url:"/range",
method:"POST",
data:{From:From, to:to},
success:function (data)
{
$('#table-wrapper').html(data);
$('#table-wrapper').append(data.htmlresponse);
}
});
}
else
{
alert("Please Select the Date")
}
});
},1000);
});
</script>
you can change the number at the end, it specifies how long you want your interval to be in ms, so right now it's set to run every 1 second.

Related

How do you implement input( or form) dependent on a select menu(drop down list)?

I'm working on grading system and I'm currently working on the form that's deals with the user entering the students results now the form I have, has 2 drop-down list(classroom, students) that are dependent. The issue and where I'm stuck is
When the user select the classroom the second drop-down menu will only show the students in that class, I have already figure that out..the issue is I want the input fields for how much subject the student is doing to appear so that the user can enter the grades for each subject specific to that student in the class
Eg if I select classroom 1b and selected student Mary.. if Mary is doing 5 subjects then 5 input field should appear so that I can enter the mark for the subjects
Link with a video showing what I'm talking about video showing an examplehttps://drive.google.com/file/d/11FoCZyOBVdUhTcvCqA1Ke0fEgRmMVC-G/view?usp=drivesdk
Models.py
Class Classroom(models.Models): name = models.charfield()
Class marks (models.Models): classroom = models.foreignkey(Classroom) Grade = models.Floatfield()
Html form
<div class="container-fluid">
<form id="result-form" method="post">
{% csrf_token %}
<!-- Modal -->
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel"> {% block modal-title%} Add Result {% endblock%}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12" id="msg8" style="font-size: 2rem; color:rgb(255, 144, 47)"></div>
<div class="col-md-12 form-group p-2">
<label class="form-label">Class Name</label>
{% render_field form.room class+="form-control" %}
</div>
<div class="col-md-12 form-group p-2">
<label class="form-label">Exam Name</label>
{% render_field form.exam class+="form-control" %}
</div>
<div class="col-md-12 form-group p-2">
<label class="form-label">Student</label>
{% render_field form.student class+="form-control select2" %}
</div>
<div class="hidden" id="subject-fields"></div>
<div class="form-group mb-3 pt-2">
<button type="button" id="resBtn" class="btn btn-info" title="Add">Submit</button>
</div>
</div>
</div>
</form>
</div>
{% block script%}
{% endblock%
script
$(document).on('click', '#submit-btn', function(event){
var response_data = []
var subject_name= $('.course');
var subject_objs = $('.subject_id');
for(i=0;i<subject_name.length;i++){
var subject_id = $(subject_objs[i]).find('input').val();
var grade_input = {
"Marks": subject_id,
}
response_data.push(grade_input);
}
$.ajax({
type: "POST",
url: "{% url 'marks' %}",
data: response_data,
success: function(response){
alert("Success");
}
});
});
This is how your view should look like.
def question_choice_view(request):
if request.method == "POST":
question_choice_data = request.POST['data']
I am not a jQuery User. As far as i can see i would put a eventlistener on the student form via .addEventListener('change', (event)See here. This would fire a function every time something changes on the select option. With that you could also collect the selected option values of the classroom and student name and make a request to get the subject names for the chosen student. After successful response i would insert the subject fields via JavaScript in the DOM.
**
function createInput(item) {
// This function takes a item and creates a new input
var newLabel = ' <br><label for="$item-mark">$item:</label>'
var newInput = '<input type="text" id="$item-mark-id" name="$item-mark"><br><br>';
newLabel = newLabel.replaceAll("$item", item)
newInput = newInput.replaceAll("$item", item)
// combine into a single str
newInput = newLabel + newInput
var studInput = document.getElementById("student-id");
// insert element inputs after student
studInput.insertAdjacentHTML('afterend', newInput);
}
function cleanOldInputs(item) {
var oldELement = item + "-mark-id"
oldELement = document.getElementById(oldELement)
if (oldELement) {
// remove old label and input
oldELement.previousSibling.remove()
oldELement.remove()
} else {}
}
function getAPIcall() {
// This is what your API sends
var responsObject = ["writing", "creativity"];
// loop throug
responsObject.forEach(item => {
// if you already picked a student clean old inputs from DOM
cleanOldInputs(item)
// send to function for input creation
createInput(item)
})
}
// get the Student Input
var studentSelect = document.getElementById("student-id");
studentSelect.addEventListener("click", function() {
// Fire anything you like
getAPIcall()
});
<form action="/action_page.php">
<label for="student">Choose a student:</label>
<select name="student" id="student-id">
<option value="harry">harry</option>
<option value="ivy">ivy</option>
</select>
</form>
Quick and dirty**

how to dynamically show form input fields base on user selection from dropdown options

I have this form that is used to enter student grades per subject now on this form I have 3 dropdown boxes that are dependent on each other, what I want to accomplish is that after the user selects the classroom that the students are in, I want the input fields for each subject to appear on the same form that is only in that class that the user selected so that the user can enter the grades of the students per subject but I am having a hard time figuring out how to implement such behavior. in short,i want to show input fields for subjects base on the classroom the user selected
form.py
<div class="container-fluid">
<form id="result-form" method="post">
{% csrf_token %}
<!-- Modal -->
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel"> {% block modal-title%} Add Result {% endblock%}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12" id="msg8" style="font-size: 2rem; color:rgb(255, 144, 47)"></div>
<div class="col-md-12 form-group p-2">
<label class="form-label">Class Name</label>
{% render_field form.room class+="form-control" %}
</div>
<div class="col-md-12 form-group p-2">
<label class="form-label">Exam Name</label>
{% render_field form.exam class+="form-control" %}
</div>
<div class="col-md-12 form-group p-2">
<label class="form-label">Student</label>
{% render_field form.student class+="form-control select2" %}
</div>
<div class="hidden" id="subject-fields"></div>
<div class="form-group mb-3 pt-2">
<button type="button" id="resBtn" class="btn btn-info" title="Add">Submit</button>
</div>
</div>
</div>
</form>
</div>
{% block script%}
<script>
$(document).ready(function () {
$('#id_room').change(function(){
var url = "{% url 'load_exams' %}"
var class_id = $(this).val();
$.ajax({
url: url,
data: {
'room':class_id
},
success: function(data){
$("#id_exam").html(data)
}
})
})
$('#id_room').change(function () {
var url = "{% url 'load_students' %}"
var class_id = $(this).val();
$.ajax({
url: url,
data: {
'room': class_id
},
success: function (data) {
$("#id_student").html(data)
}
})
})
$('.select2').select2({
placeholder: 'Please Select Here',
width: '100%',
dropdownParent: $('#addmodal')
});
$('#resBtn').click(function () {
let room = $('#id_room').val();
let exam = $('#id_exam').val();
let student = $('#id_student').val();
let csr = $('input[name="csrfmiddlewaretoken"]').val();
if (room == '' && name == '') {
$('#msg4').html('All fields are required').fadeIn('slow');
$('#msg4').delay(7000).fadeOut('slow');
} else {
mydata = {
exam: exam, csrfmiddlewaretoken: csr, room: room, student: student
};
console.log(mydata)
$.ajax({
url: "{% url 'add-result' %}",
data: mydata,
type: 'POST',
success: function (data) {
if (data.status == 'Save') {
$('#msg8').html('Result Successfully Added').fadeIn('slow');
$('#result-form')[0].reset();
$('#msg8').delay(3000).fadeOut('slow');
setTimeout(function () {
$('#addmodal').modal('hide')
}, 3000)
location.reload()
} else {
alert('Error with saving form')
}
}
})
}
});
})
</script>
{% endblock%}
forms.py
# deal with entering results
class ResultForm(forms.ModelForm):
class Meta:
model = Result
fields = ["room", "exam","student","percentage"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["exam"].queryset = Exam.objects.none()
if "room" in self.data:
try:
class_id = int(self.data.get("room"))
self.fields['exam'].queryset = Exam.objects.filter(room=class_id).order_by('name')
except(ValueError,TypeError):
pass
elif self.instance.pk:
self.fields['exam'].queryset = self.instance.classroom.exam_set.order_by('name')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["student"].queryset = Exam.objects.none()
if "room" in self.data:
try:
class_id = int(self.data.get("room"))
self.fields['student'].queryset = Student.objects.filter(room=class_id).order_by('name')
except(ValueError, TypeError):
pass
elif self.instance.pk:
self.fields['student'].queryset = self.instance.classroom.exam_set.order_by('name')
# deal with entering grade per subject
class MarkForm(forms.ModelForm):
class Meta:
model = Mark
fields = ["result", "course","grade"]

Detecting change in second dropdown (cascading) using HTML & Javascript

I'm having some trouble capturing a change in the second dropdown of a cascading dropdown. Basically my set up is this: the user first picks an ETF from the first dropdown. Upon picking an ETF, a change function detects the selection, sends it to Python using AJAX and populates the second dropdown based on the holdings within the ETF (cascading). This part works perfect. For the second dropdown, I want the user to select a visual and then that selection would be sent to Python as well and then a graph would be produced. I have not gotten to that point yet, but I'm trying to just flash a message letting me know that it is working, but for some reason the second change function does not work.
Here is the HTML:
<body> id="body" name="body">
<div class="container">
<h1 align="center">Welcome to the Alpaca Pair Trading Application! </h1>
<div class="row">
<div class="col-md-6">
<label>Select ETF</label>
<select name="etfs" data-live-search="true" id="etfs" class="form-control" class="selectpicker" title="Select ETF">
{% for etf in etfs %}
<option value="{{etf}}">{{etf}}</option>
{% endfor %}
</select>
</div>
<div class="col-md-6">
<label>Select Visual</label>
<select name="visuals" data-live-search="true" id="visuals" class="form-control" class="selectpicker" title="Select Visual"> </select>
</div>
</div>
</div>
<br>
{% for message in get_flashed_messages() %}
<p> {{ message }} </p>
{% endfor %}
<br>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js">
</script>
</body>
<script type="text/javascript">
$("#etfs").change(function() {
$.ajax({
type: "POST",
url: "{{ url_for('visuals') }}",
data: {
etf: $("#etfs").val()
},
success: function(data) {
var html = "";
for (var count = 0; count < data.length; count++) {
html += '<option value="' + data[count].id + '">' + data[count].visual + "</option>";
}
$("#visuals").html(html);
}
});
});
</script>
<script type="text/javascript">
$(document).on("change", "$visuals", function() {
$.ajax({
type: "POST",
url: "{{ url_for('graphs') }}",
data: {
visual: $("#visuals").val()
},
success: function(data) {
var html = "";
}
}
});
</script>
Here is the python code:
app=Flask(__name__)
#app.route("/")
def index():
etfs=['DIA','XLV','XLU','XLE','VNQ','GLD/SLV','QQQ','XLP','XLF']
return render_template("index.html", etfs=etfs)
#app.route("/visuals", methods=["POST","GET"])
def visuals():
etf_dict={'DIA':['UNH','GS','HD','MSFT','CRM'],'XLP':['PG','KO','PEP','WMT','COST'],
'XLV':['JNJ','UNH','PFE','ABT','ABBV'],'XLF':['BRK.B','JPM','BAC','WFC','C'],
'XLU':['NEE','DUK','SO','D','EXC'],'VNQ':['AMT','PLD','CCI','EQIX'],
'QQQ':['AAPL','MSFT','AMZN','GOOG','FB'],'XLE':['XOM','CVX','COP','MPC','SLB'],
'GLD/SLV':['GLD','SLV']}
if request.method == 'POST':
etf = request.form['etf']
holdings=etf_dict[etf]
options_list=[]
if etf=='GLD/SLV':
options_dict={}
options_dict['id']=etf
options_dict['visual']='GLD vs SLV'
options_list.append(options_dict)
else:
for i in holdings:
options_dict={}
options_dict['id']=etf
options_dict['visual']=i+' vs '+etf
options_list.append(options_dict)
options_list.append({'id':etf,
'visual': 'All Holdings vs ' +etf})
return jsonify(options_list)
#app.route("/graphs", methods=["POST","GET"])
def graphs():
print("inside graphs function")
if request.method == 'POST':
print("received post request from front end")
graph = request.form['visual']
flash("This worked! The graph chosen is" + graph)
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
Here is what the web app screen looks like. As you can see, when I select "XLE", it updates the second dropdown correctly, so I know the change function is working properly for the first dropdown.
Web App dropdowns
The problem is when I select a visual in the second dropdown, the other change function does not seem to be running..
I figured out that I should be using a form tag to submit the data from each of the dropdowns instead of trying to detect a change in the second dropdown..
Here is the updated HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Alpaca Pair Trading App</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.min.css">
<link rel="stylesheet" href={{url_for( 'static',filename='css/main.css' )}}>
</script>
</head>
<body>
<form action='/graphs' method='POST'>
<div class="container">
<h1 align="center">Welcome to the Alpaca Pair Trading Application! </h1>
<div class="row">
<div class="col-md-6">
<label>Select ETF</label>
<select name="etfs" data-live-search="true" id="etfs" class="form-control" class="selectpicker" title="Select ETF">
{% for etf in etfs %}
<option value="{{etf}}">{{etf}}</option>
{% endfor %}
</select>
</div>
<div class="col-md-6">
<label>Select Visual</label>
<select name="visuals" data-live-search="true" id="visuals" class="form-control" class="selectpicker" title="Select Visual"> </select>
</div>
</div>
</div>
<br>
<div class="container">
<div class="row">
<div class="col-md-4">
<input type="submit" name="next" value="Go" class="btn btn-primary">
</div>
</div>
</div>
</form>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js">
</script>
<script type="text/javascript">
$("#etfs").change(function() {
$.ajax({
type: "POST",
url: "{{ url_for('visuals') }}",
data: {
etf: $("#etfs").val()
},
success: function(data) {
var html = "";
for (var count = 0; count < data.length; count++) {
html += '<option value="' + data[count].visual + '">' + data[count].visual + "</option>";
}
$("#visuals").html(html);
}
});
});
</script>
</body>
</html>

how can i resolve the issue in displaying the ajax search results in django?

Problem
The results are being retrieved by the ajax search function but when I display the data retrieved in the selector using $(selector).htm(data) it loads whole the page with a page with correct search results.
The code is attached below with the screenshot of what I'm getting from this code for a better understanding.
JS
$('#searchsubmit').on('click', function(e){
e.preventDefault();
q = $('#search').val();
console.log(q);
updateContentBySearch(q);
});
function updateContentBySearch(q) {
var data = {};
data['search_by'] = q
// data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val();
$.ajax({
method: 'POST',
url: "{% url 'main:Search' %}",
data: {
'search_by': q,
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: function (data) {
searchSuccess(data)
}
});
}
function searchSuccess(data, textStatus,jqXHR)
{
$('#search-results').html(data);
}
HTML
<div class="row">
<div class="row justify-content-center" style="text-align:center">
<form class="d-flex col-md-6" id="searchform" method="POST">
{% csrf_token %}
<div class="input-group mb-3" style="text-align:center">
<input name="q" type="text" class="form-control" placeholder="Search" id="search">
<button class="btn btn-primary shadow px-5 py-2" type="submit" id="searchsubmit">Search</button>
</div>
</form>
</div>
<hr style="border-top: 1px solid #ccc; background: transparent;">
<div class="row" id="search-results">
{% regroup transaction by productID as ProductList %}
{% for productID in ProductList %}
///some code
</div>
{% endfor %}
</div>
VIEWS
#csrf_exempt
def search(request):
q = request.POST.get('search_by')
print(q)
product = Products.objects.all()
cart_product_form = CartAddProductForm()
transaction = transactions.objects.filter(productID__name__icontains=q,status='Enable').order_by('productID')
print(transaction)
context={
'products':product,
'transaction': transaction,
'cart_product_form':cart_product_form
}
html = render_to_string('main/home.html',context)
return JsonResponse(html,safe=False , content_type="application/json")
SCREENSHOT
Now in this screenshot u can see it showing me two banners and search bars and after the second the products from the search results are displayed. It's like it loads the whole page again within the page from the selector i have passed data too.
DOES ANYONE KNOWS HOW TO RESOLE THIS ISSUE OR WHERE I HAVE DONE WRONG.
because you render 'main/home.html' agin ! you just need send a json response with your context data and add it to web page with JS or create a new html template and render that with your context data and send that as response!

How to always get new checkboxes array, every time a different button is clicked

I'm developing an app about quizzes.
IMG1: [The added comments in this picture applies for the IMG2 too]
IMG2:
Description:
[IMG1] When one or more .js-answer-check checkbox are checked, I save the values in a js array. Then, when the #save-response button is clicked, the respective array is send to the server, to be saved in the db.
[IMG2] Then I click another question of the quiz, identified by .quiz-questions class, and when one or more .js-answer-check checkboxes of this new question are checked, the values are saved in the same js array.
The problem is that the previous checkboxes values, from the previous answers, are still present in the array, due to that answers.push(answerID).
How can I only grab the values of the respective question answers in the array each time a .quiz-questions button is clicked?
Expected values:
clicking the checkbox with label "2" in the first question => array should be [ 2 ] (the data-id="2" attribute in that checkbox)
clicking the checkboxes with label "1+3" and "8/2" in the second question => array should be [4, 5] as those checkboxes have data-id="4" and data-id="5" attributes.
Actual result: [2, 4, 5]
I tried out this code:
//if one|more options are checked...
var answers = [];
$(document).on('click', '.js-answer-check', function(){
if ($(this).is(':checked')){
var answerID = $(this).data('id');
answers.push(answerID);
} else {
var removeItem = $(this).data('id');
answers = $.grep(answers, function(value){
return value != removeItem;
});
}
});
$('#save-response').on('click', function(e){
e.preventDefault();
$.ajax({
method: 'POST',
url: Routing.generate('save_answer'),
data: { answers: answers },
success: function(resp) {
if (resp.success) {
var answersBack = resp.answers;
for (var ans in answersBack) {
console.log('answerID = ', answersBack[ans]);
}
}
//answers = [];
}
});
});
And I thought that if I do answers = [] will reset the initial array, but it didn't.
Any help is welcomed. Thanks.
LATER EDIT
<div class="row margin-top-ten">
<div class="col-6">
<input type="hidden" id="quiz-id" data-quiz="{{ quiz.id }}"/>
<div class="row question-content">{# the content (question-text + checkboxes) is coming from an AJAX request because I need to present everytime a new content based on `quiz-questions` buttons #}
</div>
</div>
</row>
<div class="row margin-top-ten">
<div class="col-12">
<button class="btn btn-primary btn-sm" type="button" id="save-response">Salveaza</button>
</div>
</div>
<div class="row margin-top-fifty">
<div class="col-12">
{% set i = 1 %}
<p>Navigator intrebari:</p>
{% for question in quiz.questions %}
<a href="" class="btn btn-info btn-sm quiz-question"
data-id="{{ question.id }}" data-quiz="{{ quiz.id }}">
{{ i }}
</a>
{% set i = i + 1 %}
{% endfor %}
</div>
</div>
The AJAX request for bringing new content for each quiz-questions buttons is:
<div class="col-12">
<div class="row">
<div class="col-12 question-text" data-question="{{ question.id }}">{{ question.content|raw }}</div>
</div>
<div class="row">
{% for answer in question.answers %}
<div class="col-12 question-answers">
<span style="display: inline-block">
<label for="">
<input type="checkbox" name="user-responses[]" class="js-answer-check" data-question="{{ question.id }}" data-id="{{ answer.id }}">
</label>
</span>
<span style="display:inline-block">{{ answer.answer|raw }}</span>
</div>
{% endfor %}
</div>
</div>
The save_answer php functionality is just returning the sent-data, for debug purposes. Nothing fancy.

Categories