marlboro
marlboro

Reputation: 264

how to refresh in a div values from a model with jquery .ajax() to django

I have a view which returns a chained object of 3 models

def test(request):
    output=itertools.chain(
        model1.objects.all(),
        model2.objects.all(), 
        model3.objects.all()
    )

    return render_to_response('test.html', {'output':output})

In the html, I added an anchor and a jQuery script, which should replace the #output with new values just from model1

<html>
<head>...</head>
<body>
<script>
    $(document).ready(function() {

        $("#switch").click(function() {
            $.ajax({
                url: $(this).attr("href"),
                success: function(result) {
                    //whatever I put here is not triggered
                }
             });
        });
    });
</script>

    <a id="switch" href="?model=1">switch to model 1</a>

    <div id="output">
        {% for item in output %}
            <div id="{{item}}">
                {{item}}
            </div>
        {% endfor %}
    </div>
</body>
</html>

I tried to put the div#output into a separate template output.html and modified the views.py like so:

def test(request, template='test.html'):

    if request.GET.get('model'):
        output=model1.objects.all()
    else:
        output=itertools.chain(
           model1.objects.all(),
           model2.objects.all(), 
           model3.objects.all()
        )

    if request.is_ajax(): template='output.html'

    return render_to_response(template, {'output':output})

But everytime I click the link, the whole page is refreshed (with the new values from model1).

Opera returns just the output.html

Been struggling with this for more than 3 days, Im new into Ajax and this is getting very confusing for me.

I hope someone can shed some light!

Upvotes: 1

Views: 894

Answers (2)

marlboro
marlboro

Reputation: 264

Thanks to Daniel Rosman for the heads-up I had to prevent the default action of the a#switch. It works like butter now!

Here is the initial question: how to access jQuery.ajax() get parameters in Django views

Upvotes: 0

BluesRockAddict
BluesRockAddict

Reputation: 15683

First, make sure that your view works and that you're getting the expected HTML output when accessing the url directly (you might also want to comment out if request.is_ajax() temporarily).

Then, try replacing the content of the #output div using jQuery.html() method in your ajax call. Here is an example with some animation:

$.ajax({

    ...
    success: function( returnedData ) {
        $("#output").css("color", "red").fadeOut(500, function() {
            $("#output").html(returnedData);
            $(this).css("color", "green").fadeIn(500);
        });
    }

Also, try monitoring your ajax call using Firebug/Chrome Developer Tools - both tools will allow you to quickly determine the issue.

Upvotes: 1

Related Questions