wxcoder
wxcoder

Reputation: 655

Javascript POST to Django using Ajax not working

I am trying to send an post request over ajax but the ajax doesn't seem to be firing. In create_post(), console.log("i'm clicked"); does shows up in the console. The print statements in monthly_query(request) don't show up in the log.

HTML:

<form method="POST" action="/create_post/" id="post-form">
<select id = "datasource">
    <option value="data1">data1</option>
    <option value="data2">data2</option>
</select>
<select id="sourceyear">
    {% for year in years %}
    <option value="Years">{{ year }}</option>
    {% endfor %}
</select>
<select id="sourcemonth">
    <option value="Monthly">1</option>
    <option value="Monthly">2</option>
    <option value="Monthly">3</option>
    <option value="Monthly">4</option>
</select>
<input type="button" value="Submit" onclick="create_post()"/>
{% csrf_token %}
</form>

Javascript:

$(document).ready(function() { 

 $('#post-form').on('submit', function(event) {
    event.preventDefault();
});

function create_post() {
        console.log("i'm clicked");
        $.ajax({
            url: "create_post/",
            cache : "false",
            type: "POST",
            dataType: 'json',
            data : { 'source': $("#datasource").val(), 'year': $("#sourceyear").val(), 'month': $("#sourcemonth").val() },

            success : function(json) {
                console.log("my json")
                $("#outgoingvalue").prepend(json.result);   
            },

            error: function(xhr,errmsg,err) {
                console.log(xhr.status + ": " + xhr.responseText);
            }  
        });
    }
}

views.py:

def monthly_query(request):
    print("request made")
    if request.method == 'POST':
        print("post request success")

urls.py:

urlpatterns = patterns (
    '',
    url(r'^$', views.metrics, name='metrics'),
    url(r'^api/graphs', views.graphs, name='graphs'),
    url(r'^create_post/$', views.monthly_query, name='create_post'),
)

EDIT: Additional javascript:

 function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {

        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    function sameOrigin(url) {
        //test that a given url is a same-origin URL
        //url could be relative or scheme relative or absolute
        var host = document.local.host;
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;

        return (url == origin || url.slice(0, origin.length + 1) == origin +'/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            !(/^(\/\/|http:|https:).*/.test(url));
    }

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if(!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {

                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

Edit: Output of beforeSend: function(xhr, settings) console.log(settings);: Object { url: "/create_post/", type: "POST", isLocal: false, global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; …", accepts: Object, contents: Object, responseFields: Object, 14 more… }

Upvotes: 0

Views: 3730

Answers (1)

masnun
masnun

Reputation: 11906

Issue - 1

In your ajax request you are requesting create_post/ which is a relative url. So if you're in /home/, the request would be sent to /home/create_post/. You should use a path relative to root. So it should be /create_post.

Issue - 2 & 3

print would display the message on your console but it does not send the string as a html response.

And you need to handle the csrf tokens. It's better to pass it as a part of the request or exempt it.

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def monthly_query(request):
    print("request made")
    if request.method == 'POST':
        return HttpResponse("post request success")

You need to return a HttpResponse from a view for it to be sent as a response from the server. The csrf_exempt decorator will exempt the view from csrf protection.

You can import it like this:

from django.http import HttpResponse

Upvotes: 3

Related Questions