How to change 2 separate parts in an HTML without Refreshing page using Ajax in a Django Project
I have a HTML template for a django project where there are 2 button on the top of a page and one at the end of the page. In the begining the top button is enabled and the lower one is disabled. My objectiveis that when a user clicks on the top button it gets disabled and the lower button gets enabled.
Currently I am at the stage that when a user clicks the top buttons gets disabled with the whole page refreshing but I want to add the lower one to it as well.
Here is the main template to have a better idea:
<!-- button -->
<div id="startworkout">
{% include 'my_gym/button.html' %}
</div>
<!-- button -->
...................................................
<!-- button -->
<div id="deactivate">
{% include 'my_gym/deactivate.html' %}
</div>
<!-- button -->
Here is the button.html:
<form action="{% url 'my_gym:bla' id=workout.id %}" method='post'>
{% csrf_token %}
{% if workout.active %}
<button disabled id="customSwitches" type="button">Close Workout </button>
{% else %}
<button value="true" id="customSwitches" type="button" >Start the workout </button>
{% endif %}
</form>
Here is the 2nd part deactivate.html of that I want to include:
<div>
{% if workout.active %}
<button id="stop" onclick="stop();" type="button">Finish Workout</button>
</a>
{% else %}
<button disabled id="stop" onclick="stop();" type="button">Finish Workout</button>
{% endif %}
</div>
Here is the script with trial commented:
<script type="text/javascript">
$(document).ready(function(event){
$(document).on('click','#customSwitches', function(event){
event.preventDefault();
var status= $(this).attr('value');
$.ajax({
type:'POST',
url:'{% url 'my_gym:bla' id=workout.id %}',
data:{'active' : status, 'csrfmiddlewaretoken':'{{csrf_token}}'},
dataType:'json',
success:function(response){
$('#startworkout').html(response['form']),
<!-- $('#deactivate').html2(response['div'])-->
console.log($('#startworkout').html(response['form','div']));
<!-- console.log($('#deactivate').html2(response['div']));-->
error:function(rs, e){
console.log(rs.responseText);
},
});
});
});
</script>
Here is the views:
def change_status(request, id):
if request.is_ajax() and request.method == 'POST':
--------------------------
if request.POST.get('active') == 'true':
-------------
context = {}
html = render_to_string('my_gym/button.html', context,request=request)
html2= render_to_string('my_gym/deactivate.html', context,request=request)
print("Sucess")
return JsonResponse({'form': html, 'div':html2})
else:
print("Fail")
else:
print("Fail")
I am currenly geting the following error in the console:
Uncaught TypeError: $(...).html2 is not a function