carol Alex
carol Alex

Reputation: 353

Ajax get new values from Django 1.9 code on button click

I'm trying to write a code where status of servers (AWS instances) can be returned to a browser when users want to check the status.Sometimes it may take a while for servers to start up so I want to have the value of the status refreshed (run the Django code again to get new value) each time a user clicks the button.
Example:
[Check Status] (button)
WebServer-Test running (this line gets refreshed each time the button is clicked)

As of now, I'm not sure how to get view.py to run again and return the new value for the html page to use.

This is my view.py

def indcheckstatus(request, question_id, check_id):
    inst() #runs an update on the instance (instance2[0].update() etc.)
    text1 = 'WebServer-Test %s' % instance1[0].state
    text2 = 'Gluster %s' % instance2[0].state
    text3 = 'Gluster2 %s' % instance3[0].state
    text4 = 'Database %s' % instance4[0].state
    txt1 = 'WebServer-Test'
    txt2 = 'Gluster'
    txt3 = 'Gluster2'
    txt4 = 'Database-Test'
    if check_id == '1': 
        return render(request, 'awsservers/indcheckstatus.html', {'indstatus': text1, 'indserver':txt1})
    elif check_id == '2':
        return render(request, 'awsservers/indcheckstatus.html', {'indstatus': text2, 'indserver':txt2})
    elif check_id == '3':
        return render(request, 'awsservers/indcheckstatus.html', {'indstatus': text3, 'indserver':txt3})
    elif check_id == '4':
        return render(request, 'awsservers/indcheckstatus.html', {'indstatus': text4, 'indserver':txt4})

this is my ajax code + html code

<html>
<body>
<title>Server Management</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#state").hide()
    var clicking = 1
    $("#button").click(function() {
        $.ajax({
            url : '',
            success : function(response) {
                clicking++
                $('#result').html($('#state').html() + clicking);
                }
            });
        return false;
    });
});

</script>

<noscript>
    Some features require Javascript enabled
</noscript>

<form method="post">
    {%csrf_token%}
    <input id="button" type="button" value="Check Status"></input>
</form>

<div id="result">
{{ indserver }}
</div>

<div id="state">
{{ indstatus }}
</div>

<h2>Status of {{ indserver }}</h2>
<p>{{ indstatus }}</p>

<a href="{% url 'awsservers:index' %}">Go Back</a> 

</body>
</html>

The whole point is that I don't want to have the entire page refreshed to load the new value but I would like the value refreshed whenever the button is clicked.

I'm extremely new to Django and especially Ajax so please pardon me if my code isn't very "proper" :) I do appreciate the help! Please let me know if there is a better way to load new values from Django as well!

Upvotes: 1

Views: 1009

Answers (1)

carol Alex
carol Alex

Reputation: 353

So I was able to find a solution to this.

this is my updated views.py

def indcheckstatus(request, question_id, check_id):
    inst() // does an update of all instances
    text1 = 'WebServer-Test %s' % instance1[0].state
    text2 = 'Gluster %s' % instance2[0].state
    text3 = 'Gluster2 %s' % instance3[0].state
    text4 = 'Database-Test %s' % instance4[0].state
    txt1 = 'WebServer-Test'
    txt2 = 'Gluster'
    txt3 = 'Gluster2'
    txt4 = 'Database-Test'
    if request.is_ajax():  // what to do if ajax code calls function
        if check_id == '1':
            return HttpResponse(text1) // return updated status back to html
        elif check_id == '2':
            return HttpResponse(text2)
        elif check_id == '3':
            return HttpResponse(text3)
        elif check_id == '4':
            return HttpResponse(text4)
    else:
        if check_id == '1':
            return render(request, 'awsservers/indcheckstatus.html', {'indstatus': text1, 'indserver':txt1})
        elif check_id == '2':
            return render(request, 'awsservers/indcheckstatus.html', {'indstatus': text2, 'indserver':txt2})
        elif check_id == '3':
            return render(request, 'awsservers/indcheckstatus.html', {'indstatus': text3, 'indserver':txt3})
        elif check_id == '4':
            return render(request, 'awsservers/indcheckstatus.html', {'indstatus': text4, 'indserver':txt4})

this is my html + ajax code:

<html>
<body>
<title>Server Management</title>
<p>{{ indserver }} is starting up. </p>

<p>Click the button below to get the status of the server</p>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#state").hide()
    $("#start_id").hide()
    $("#button").click(function() {
        if ($("#start_id:contains('1')").length) {   // to check which server was picked
            $.ajax({
                type: "get",   // requesting updated values from django
                url : '/menu/2/1/status-ind',   // determines which function is called
                success : function(response) {
                    ($('#result').html(response)); 
                } // response is basically "[ServerName ServerState]" form (seen from code above)
            }); 
        }
        else if ($("#start_id:contains('2')").length) {
        ...... // do code 
        }
        return false;
    }); 
});

</script>
<noscript>
    Some features require Javascript enabled
</noscript>
<form method="post">
    {%csrf_token%}
    <input id="button" type="button" value="Check Status"></input>
</form>

<div id="result">
{{ indserver }}
</div>

<div id="state">
{{ indstatus }}
</div>

<div id="start_id">
{{ start_id }}
</div>
<br>
<a href="{% url 'awsservers:index' %}">Go Back</a>
</body>
</html>

I've added comments in my code to explain the changes I've done. I realised I had to write the url associated with the function needed to get the updated values and from there write the correct response on my views.py to be used on the ajax code. It works perfectly now!

Upvotes: 1

Related Questions