Search code examples
jquerypythonajaxpyramidjinja2

calling python method has no affect on client side with jinja2


I have a template page which gets displayed when the user visits the url (http://mysite/new_device)

    config.add_route('new_device', '/new_device')

views.py method:

@view_config(route_name="new_device", renderer='templates/main.html')
def new_device(request):
    do stuff......
    return dict(title=title, partial=partial, deviceTypes=deviceTypes, sections=sections)

When I go to that link, the page is displayed correctly with jinja2 printing all arrays and dictionaries that are passed in the return statement of my python method.

On my page I have a select tag which has a bunch of option which the user can select(Transformer, switchboard etc), and it will load the fields according to the selected option(ajax call to get data). What I am trying to do is use jquery and ajax to load the appropriate fields by checking for change on the select that I have, obtaining the id, then doing an ajax call to the python method new_device.

$("#deviceTypes").change(function () {
    var deviceTypeID = $(this).val();

    var data = {
        "deviceTypeID": deviceTypeID
    }

    $.ajax({
        url: "http://127.0.0.1:6543/new_device",
        type: "POST",
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8',
        success: function (response, textStatus, jqXHR) {
        },
        error: function (jqXHR, textStatus, errorThrown) {
            //change this back to error throwing after wards
            alert("error");
        }
    });
});

The problem I have is the data is being returned from the method, but the client isn't being updated with the new information.

This is a snippet of my html page

    <select id="deviceTypes" class="inputBoxes">
        {% for key, value in deviceTypes.iteritems() %}
        <option value="{{key}}">{{value}}</option>
        {% endfor %}
    </select>

    <br />
    {% for sec in sections %}
        <label class="inputBoxLabels">{{sec}}</label><br />
    {% endfor %}

In other words, jinja2 here isn't printing the newly returned information. Can it only access the data once on the initial load or how does this work?


Solution

  • After thinking it through for a bit I have come up with a solution. in my url I simply added a deviceTypeID paramter

    config.add_route('new_device', '/new_device/{deviceTypeID}')
    

    Then whenever the user selects an option from the list, I simply redirect the page to that id which then loads he newly returned data from my python method

        $("#deviceTypes").change(function () {
        var deviceTypeID = $(this).val();
    
        var data = {
            "deviceTypeID": deviceTypeID
        }
    
        window.location = "http://127.0.0.1:6543/new_device/" + deviceTypeID + "/0"
    });