Wagh
Wagh

Reputation: 4306

Not stisfying the condition if request.is_ajax(): in django view

I am trying to Configure the URL and view to check if javascript is calling the view or not using the ajax call. I am able to Pass this JSON data using AJAX POST method to the django URL. But in view its not entering in to the condition if request.is_ajax(): it directly goes to the else part in view.

views.py

@csrf_exempt    
def lat_ajax(request):
    if request.is_ajax():
        if request.method == 'POST':
            data = request.POST.all()
            print data
            return HttpResponse(json.dumps({'data': data}), content_type="application/json")
    else :
        print "you are not in ajax"
        return render_to_response('poll/ajax_test.html', locals())

ajax request

var data1 = JSON.stringify(data);
            console.log(data1)
            //alert(data1)
            alert("hi")
            $.ajax({
                    url: "http://127.0.0.1:8000/poll/lat_ajax/",
                    type:"POST",
                    data: data,
                    contentType:"jsonp",
                    dataType: "jsonp",
                    success:function(response){
                                        alert ("resp: "+response.data);
                                        alert("you in ajax")
                    }

            });

            return false;

                });

This html page is not from the same project. I am using the django project url to pass data and then send that data to one email address without saving it. Is this a cross domain problem? In chrome i am getting the error

XMLHttpRequest cannot load file:///C:/test.everycrave.com/contact/contact.php. Received an invalid response. Origin 'null' is therefore not allowed access. contact.html:1
Resource interpreted as Script but transferred with MIME type text/html: "http://127.0.0.1:8000/poll/lat_ajax/?callback=jQuery18102593700629658997_13…1%40gmail.com&subject=Fwd%3A+DB+design&message=sdfsddfsfds&_=1399357203734". jquery.js:3
send jquery.js:3
p.extend.ajax jquery.js:3
(anonymous function) contact.html:256
p.event.dispatch jquery.js:3
g.handle.h

Please help me out.

Upvotes: 0

Views: 2090

Answers (1)

freakish
freakish

Reputation: 56547

Yes, it's an issue with cross domain requests. Normally the server has to tell you which HTTP headers it accepts when you are doing CORS. In order to use .is_ajax() the request has to contain

X-Requested-With: XMLHttpRequest

header (that's exactly what .is_ajax() checks). But by default the HTTP standard forbids to send that header via CORS. So to make it work your server not only has to send Access-Control-Allow-Origin header but also

Access-Control-Allow-Headers: X-Requested-With

Then you have to set that header in your request manually:

$.ajax({
    // some settings
    headers: {'X-Requested-With': 'XMLHttpRequest'}
});

EDIT I've just realized that you are actually doing JSONP, which is not CORS. In that case there is no way to set that header since JSONP is not AJAX at all. It is only wrapped to look like AJAX, but what actually happens under the hood is that the browser creates a <script> tag that points to the URL. It is impossible to change that. I advice switching to CORS. Other possibility is to send additional info in URL (as a query string). Not elegant but it will work.

Upvotes: 1

Related Questions