Oleksii Petrushynskyi
Oleksii Petrushynskyi

Reputation: 373

500 (Internal Server Error) AJAX Django

all! Can u please help me? I have a small problem. When i click button, When I click on a button, a new object should be created without reloading the page. Only one parameter is required to create an object.

The problem is that when you click the object is created (the new object is displayed in the admin panel), but in the console js there is an error: Failed to load resource: the server responded with a status of 500 (Internal Server Error)

JS:

function initBuyButton(){
    $('.button-buy').click(function(e){
        e.preventDefault();
        var test = $(this);
        var smartphone_id = test.data("smartphone_id");
        var url = test.attr("action");

        basketUpdating(smartphone_id, url);
    });
}


function basketUpdating(smartphone_id, url){
    var data = {};
    var csrf_token = $('#form_buying_product [name="csrfmiddlewaretoken"]').val();

    data["csrfmiddlewaretoken"] = csrf_token;
    data.smartphone_id = smartphone_id;

    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        cache: true,
    });
}


$(document).ready(function(){
    initBuyButton();
});

View:

def basket_adding(request):
    """Add new smartphone to basket."""
    data = request.POST
    smartphone_id = data.get('smartphone_id')
    SmartphoneInBasket.objects.create(smartphone_id=smartphone_id)

    return True

HTML:

<form id="form_buying_product" > {% csrf_token %}
  {% for sm in smartphones %}
 ...    
    <input type="submit" action="{% url 'basket_adding' %}" class="button-
     buy" data-smartphone_id = "{{ sm.id }}" value="Buy">
  {% endfor %}
</form>

Upvotes: 0

Views: 3856

Answers (3)

King Reload
King Reload

Reputation: 2962

You need to include the csrf token as a header.

var csrftoken = $("[name=csrfmiddlewaretoken]").val();

$.ajax({
    url: url,
    type: 'POST',
    headers:{
        "X-CSRFToken": csrftoken
    },
    data: data,
    cache: true,
});

Because an error 500 is that your permission gets denied to send the data.

Upvotes: 1

thebjorn
thebjorn

Reputation: 27351

I have the following helper functions defined:

import json

def json_response(request, val, **kw):
    """Return a json or jsonp response.
    """
    if request.GET.get('callback'):
        return jsonp(request.GET['callback'], val, **kw)
    else:
        return jsonval(val, **kw)

def jsonval(val, **kw):
    """Serialize val to a json HTTP response.
    """
    data = dumps(val, **kw)
    resp = http.HttpResponse(data, content_type='application/json')
    resp['Content-Type'] = 'application/json; charset=UTF-8'
    return resp

def jsonp(callback, val, **kw):
    """Serialization with json callback.
    """
    data = callback + '(%s)' % json.dumps(val, **kw)

    return http.HttpResponse(
        data,
        content_type='application/javascript; charset=utf-8'
    )

with those defined your view can return a json object (to your ajax call):

def basket_adding(request):
    """Add new smartphone to basket."""
    ...
    return json_response(request, True)

it's common practice to return an object though, so perhaps:

    return json_response(request, {"status": True})

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599946

As mentioned in the comments, a view needs to return an HttpResponse. If you want, it can be n empty:

return HttpResponse()

Upvotes: 3

Related Questions