Drwhite
Drwhite

Reputation: 1695

method change ajax with django

I have the following inputs:

<input id="country_name" type"text" />
<input id="country_id" type"text" />

And I want to affect the id corresponding to the country that I insert into the country_name input with onchange. So I use this ajax function :

$("#country_name").change({
    $.ajax({
        url: "/country/getid/",
        method: 'GET',
        datatype: "json",
        data: {'country_name': $("#country_name").val()},
        success: function(response) {   
            $("#country_id").val() = response.country_id;
        }
    });
});

And my view is like this (linked to the same url in urls.py)

def get_country_id(country_name_get):
    countries = Countries.objects.filter(country_name=country_name_get)
    if countries.exists():
        for country in countries:
            country_id = country.country_id
    else:
        country_id = ''
return country_id 

in my urls.py i have add this line :

url(r'^/country/getid/$', 'des.services.get_country_id', name='get_country_id'),

i have inspected the element with Google Chrome and then i see this error:

Uncaught SyntaxError: Unexpected token .

do you have any idea where the error came from ?

I still get nothing in the country_id input. Is there a problem with my code or is there another solution for that?

Upvotes: 0

Views: 321

Answers (3)

pemistahl
pemistahl

Reputation: 9584

Your view does not return an HttpResponse. Moreover, you should return your country_id as JSON data. Assuming that each country name can only appear once in your database, your for loop in the view does not make any sense since you only retrieve the country_id for the last country_name that is in your queryset. Also, you should name your Django models always as singular words, not plural, that is, Country instead of Countries.

I would rewrite your AJAX function and your view like this:

$("#country_name").change({
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: "/country/getid/",
        data: {'country_name': $("#country_name").val()},
        success: function(response) {   
            $("#country_id").val() = response.country_id;
        }
    });
});

The view:

import json
from django.http import HttpResponse

def get_country_id(request):
    country_name = request.GET['country_name']
    response = {}

    try:
        country = Countries.objects.get(country_name=country_name)
        response['country_id'] = country.country_id
    except Countries.DoesNotExist:
        response['country_id'] = ''

    return HttpResponse(json.dumps(response), mimetype='application/json') 

Upvotes: 3

catherine
catherine

Reputation: 22808

Your url in ajax must have an app_name. I don't know what exactly the name of your app so I put app_name in my sample. Just change it with the correct one.

$("#country_name").change({
    $.ajax({
        type: "GET",
        url: "/app_name/country/getid/",
        data: {'country_name': $("#country_name").val()},
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function(data) {   
            $("#country_id").val() = data;
        }
    });
});

you must pass the request, not country_name_get

def get_country_id(request):
    country_name = request.GET['country_name']

    try:
        country = Countries.objects.get(country_name=country_name)
        country_id = country.id
    except Countries.DoesNotExist:
        country_id = ''

    return HttpResponse(country_id) 

In your url, I have doubt because of this des.services.get_country_id, it must be

 urlpatterns = patterns('app_name.views',
      url(r'^country/getid/$', 'get_country_id', name='get_country_id'),
 )  

Or

 urlpatterns = patterns('',
      url(r'^country/getid/$', 'app_name.views.get_country_id', name='get_country_id'),
 )

depends on how you define it

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599956

A view has to return an HttpResponse. The content of that response can be a simple ID, if you like, but it still has to be wrapped in a response.

return HttpResponse(country_id)

If you'd looked at the console, or the developer tools in your browser, you would have seen that the view was returning a 500 error. The browser tools would also have shown you the error traceback itself, which would have said exactly what I say above.

Upvotes: 1

Related Questions