Django AJAX error: Cross origin requests are only supported for protocol schemes

I am getting the following error regarding AJAX call

XMLHttpRequest cannot load billbrain:sellbill. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

billbrain is my django app name while sellbill is the url name for the selling invoice view.

Following is my AJAX (Django) code:

$.ajax({
        url : "billbrain:sellbill", 
        type : "POST", d
        data : { customer_code: input }, // data sent with the post request

                // handle a successful response
        success : function(json) {
            console.log(json); // log the returned json to the console
            console.log("success"); // another sanity check
        },
    });

Now, if explicitly state the url that would violate DRY. So, what is the best practice?

Answers 1

  • You should pass csrf token and you couldn't write like this in url of ajax. you should write like below code.

    If you have in-line js. It will work for you otherwise you should add two variables into template which is rendering. because, you can't use django's variable into imported JS.

    This code just put into bottom of template.

    <script>
     url_sellbill = '{% url 'billbrain:sellbill' %}';
     csrf_token = '{{ csrf_token }}';
    </script>
    

    Below code put into your js.

    $.ajax({
            url : url_sellbill,
            type : "POST", d
            data : { 
                    customer_code: input,
                    'csrfmiddlewaretoken': csrf_token,
    
            }, // data sent with the post request
    
            // handle a successful response
            success : function(json) {
                console.log(json); // log the returned json to the console
                console.log("success"); // another sanity check
            },
        });
    

    Hopefully, It will work for you. :)


Related Articles