Praful Bagai
Praful Bagai

Reputation: 17382

Django Ajax-Jquery does not fetch the data

I am not able to get the input text field data with id city_name from the form via jQuery-Ajax method.

The error that I keeps getting is "NetworkError: 403 FORBIDDEN - http://127.0.0.1:8000/dashboard".

I know how to get the data using hidden field type, but that option cannot be used here and moreover, getting data from hidden field is now an outdated method. So, how can I get data using Django-AjaxJquery method.

HTML

<form type = "POST">
            {% csrf_token %}    
            <input type="text" placeholder = "Enter City Name" id = "city_name">
            <input type="button" value = "On" id="on">
            <input type="button" value = "Off" id="off">
</form>

JS File

$(function(){

    $("#on").click(function (event) {
        event.preventDefault();

        $.ajax({
            type: "POST",
            url: "dashboard",
            data : {
                'city_name' : $("#city_name").val(),
                   },

               });
    });
});

View.py

@login_required
def dashboard(request):
    ctx = {}

    if request.is_ajax():
        city_name = request.POST['city_name']
        print city_name

    return render_to_response('dashboard/dashboard.html',ctx, context_instance = RequestContext(request))

urls.py

urlpatterns = patterns('',
    url(r'^dashboard$','apps.dashboard.views.dashboard', name = 'llumpps_dashboard'),

    )

Upvotes: 1

Views: 491

Answers (1)

Hieu Nguyen
Hieu Nguyen

Reputation: 8623

It is missing the CSRF token in the request.

You can either use @csrf_exempt decorator for your view like:

@login_required
@csrf_exempt
def dashboard(request):
    ...

Or send the token along with the request:

$.ajax({
    type: "POST",
    url: "dashboard",
    data : {
        'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val();
        'city_name' : $("#city_name").val(),
    },
    complete: function () {
        // do whatever here
    }
});

Read more about CSRF and AJAX in Django here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

Hope it helps.

Upvotes: 4

Related Questions