[Answer]-How we can use ajax() in views.py in django?

1👍

In general, $.ajax method sends an asynchronous http request.

You can read about it here.

First argument is url, where we send request.

Second, is request method it may be GET, POST, PUT, DELETE and etc. see wiki

Third argument is key-value dictionary with data, which you use in server-side.
In django, you may access it in request.POST(in case of post request)

Fourth argument is function, which is invoked when server succesfully returns response.
You do not need if statement in this function, because when request fails or server does not give a response, or server returns error(something like 40* code for example) this function will not be invoked.

This function takes one argument with server’s response. You need handling this data, for example showing user a message like Invalid data, please correct errors... or Valid data. your request is in process now. and staff like that.

Last argument is data type of servers response. jQuery is smart enough to parse json or html for you, so in this case, response(argument of success function) is pure JS object, deserialized from JSON.

In your server-side(Django views) you must do some validation of request’s data. and do something with it. For example, save it to database. When i have to implement ajax form processing i do sumething like this:

if request.method == 'POST':
    response = {}
    form = UploadForm(request.POST, request.FILES, user = request.user)
    if form.is_valid():
        form.save()
        response['success'] = 1
    else:
        response['success'] = 0
        response['errors'] = dict(form.errors)
    return HttpResponse(simplejson.dumps(response), mimetype = 'application/json' )

And on client side, in js something like this

$.post('/url/to/view',
       function(json){
           if(json['success']){
               alert('Yahooo! Successfull request')
           }
           else{
               alert('Oooops. Looks like you send invalid data')
           }
       }, 'json')

Good luck!

Leave a comment