Hellnar
Hellnar

Reputation: 64823

Django and Ajax based model saving

via ajax, I want to post some data and if model successfully gets saved, returns answer as a JSON object.

Here is my jquery based ajax post:

var requestData = { 'ievent_id': type , 'channel_id': CHANNEL_ID , 'start_date': dateToStrConverter(start_date) , 'end_date': dateToStrConverter(end_date) };
$.ajax({
    type: "POST",
    url: "my-ajax-url/",
    data: requestData,
    dataType: "json",
    success: function(data){
        console.log( "ID:" + data.plan_id + " Error:" + data.error);
    },
    error: function(msg){
        alert( "Theres an error with the server." );
    }              
});

And my Django view that handles this ajax call to save iEventPlan objects and return response:

from django.utils import simplejson as json

def planner_save_view(request):
    if request.method == "POST" and request.is_ajax():
        root = json.loads(request.raw_post_data[0])

        ##data
        ievent = iEvent.objects.get(pk = root['ievent_id'])
        channel = Channel.objects.get(siservice = root['channel_id'])
        start_date = datetime.strptime(root['start_date'],'%d-%m-%Y %H:%M')
        end_date = datetime.strptime(root['end_date'],'%d-%m-%Y %H:%M')
        response_dict = {}
        try:
            plan = iEventPlan(red_button=ievent,channel=channel,start_date=start_date,end_date=end_date)
            plan.save()
            response_dict.update({'plan_id': plan.id})
        except:
            response_dict.update({'error': "theres a problem."})
        return HttpResponse(json.dumps(response_dict), mimetype="application/json")
    else:
        HttpResponse("Not authorized.")

This is the error I get:

JSONDecodeError at /my-ajax-url/

No JSON object could be decoded: line 1 column 0 (char 0)

What I am doing wrong? I will be grateful if you show me the proper way of handling ajax based django model savings and responses.

Upvotes: 2

Views: 2394

Answers (2)

lqc
lqc

Reputation: 7328

You're sending POST data in the standard form encoding. The dataType attribute doesn't specify type of data to send, but the one you expect to receive. If you really want to send JSON from your browser, you should do something like this:

  $.ajax({
    data: JSON.stringify(data),
    processData: false,
    contentType: 'application/json',
    // other options
  }

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599698

jQuery's .ajax() function doesn't post data as raw JSON. It uses the standard form-encoded format (the dataType parameter is to determine what format it is expecting the response from the server).

So instead of the json.loads() call, you should just do this:

root = request.POST

Upvotes: 1

Related Questions