Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data back from django views.py and using ajax to display it

EDITED

I'm trying to use jquery/ajax to display data returned from a django method.

I have a html button called keywordBtn. So when it's pressed, the updateKeywordSubscribed method will be called.

however, my object is not being returned by django. Is there something wrong with my method?

If successful, the div section name "update" would display the list of words in that json list.

what i have in my html:

<script type="text/javascript">
        $(document).ready(function() { 
            $("#keywordBtn").click(function(e) { 
                updateKeywordSubscribed(e, "#keywords"); 
            });
        });
        function updateKeywordSubscribed(e, keywords) {
            e.preventDefault();
            var option_form = jQuery(e.target);
            $.ajax({
                url : option_form.attr('action'),
                type : option_form.attr('method'),
                data : option_form.serialize(),
                dataType : 'json',
                success : function(response) { alert ('sometext')})
        }
</script>

what i have in my views.py:

def keyword_subscribe(request):
    if 'keyword_input' in request.POST:
    if 'name_input' in request.POST:
        xhr = request.GET.has_key('xhr')
        response_dict = {}
            new_keyword = request.POST['keyword_input']
        username = request.POST['name_input']
        response_dict.update({'keyword_input': new_keyword, 'name_input': username})
        power_keyword = subscribe_keyword(username,keywords)
        if power_keyword:
            response_dict.update({'success':True})
        else:
            response_dict.update({'errors':{}})
            if not username:
                        response_dict['errors'].update({'name_input': 'User ID is required'})
                if not total and total is not False:
                        response_dict['errors'].update({'keyword_input': 'Keyword field is blank'})
        if xhr:
                return HttpResponse(simplejson.dumps(response_dict), mimetype='application/javascript')
            return render_to_response('r2/userprofile_list.html', response_dict)
like image 290
Stanwin Siow Avatar asked Feb 27 '12 13:02

Stanwin Siow


People also ask

How do I get data from my AJAX post to my Django view?

To send and receive data to and from a web server, AJAX uses the following steps: Create an XMLHttpRequest object. Use the XMLHttpRequest object to exchange data asynchronously between the client and the server. Use JavaScript and the DOM to process the data.

Can you use AJAX with Django?

Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application.

How send data from get in AJAX?

post(URL,data,callback); The required URL parameter specifies the URL you wish to request. The optional data parameter specifies some data to send along with the request. The optional callback parameter is the name of a function to be executed if the request succeeds.


1 Answers

I'm doing something similar to what you need in my current project.

I GET this zipcode view which returns a geojson result or null

My View:

def get_zipcode(request, latitude, longitude):
    # Point on a map
    point = GEOSGeometry('POINT(%s %s)' % (longitude, latitude))

    try :
        zipcodes = Zipcode.objects.filter(mpoly__contains=point)
        return HttpResponse(zipcodes[0].mpoly.geojson, mimetype="application/json")
    except :
        return HttpResponse(json.dumps(None), mimetype="application/json")

my mimetype is application/json not application/javascript

My urls:

url(r'^collision/zipcode/(?P<latitude>(\-|)\d+\.\d+)/(?P<longitude>(\-|)\d+\.\d+)/', 'core.views.get_zipcode', name='collision-zipcode'),

The JS that makes the call and handles the json result

$.ajax({
    url : '/collision/zipcode/' + latitude + '/' + longitude + '/',
    dataType : 'json',
    type : 'GET',
    success: function(data)
    {
        var paths = coord_to_paths(data.coordinates); 
        var polygon = new google.maps.Polygon({ 
            paths : paths, 
            strokeColor : "#FF7800", 
            strokeOpacity : 1, 
            strokeWeight : 2, 
            fillColor : "#FF7800", 
            fillOpacity : 0.6
        });

        polygon.setMap(map);

        console.log("adding zipcode polygon");
    }
});

note that if you are doing retrieving json, if you set the dataType to 'json', you should be go to access data in your success function as a JS native.

if you need to debug what data is actually being retrieved by jquery, do a

console.log(data);
and look in your dev console w/i your browser (chrome/ff I dont know if other browsers support this)
like image 190
Francis Yaconiello Avatar answered Oct 26 '22 05:10

Francis Yaconiello