0

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… }

7
  • can you manually navigate to it in the browser? Commented Jan 12, 2016 at 18:41
  • @Busturdust it's say views.monthly_query didn't return an HttpResponse object Commented Jan 12, 2016 at 18:43
  • you are printing a string, not returning an HTTPResponse Commented Jan 12, 2016 at 18:46
  • @Busturdust I added return HttpResponse(" ") and that didn't make a difference. When you meant navigate to it, you meant /create_post correct? Commented Jan 12, 2016 at 18:47
  • you may also need a status=200 to sy,mbol success. you should reserach more about HTTP communication Commented Jan 12, 2016 at 18:49

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

10 Comments

print("request made") does not even show up in the log after clicking submit. I made the changes showed in your post.
Please change your ajax request url to be /create_post/ - add the beginning slash.
console.log(json) to see what the server returns!
function(json) never gets executed
Then the error gets called? Either one has to be called. Also check your console logs for possible JS errors.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.