1

I'm currently working on a webpage that has a form in the Django view. This form takes the name of an artist, a city, and a state in its input fields. These input values will eventually be concatenated to a url which links to a JSON file for concert data (when I get to that part), but currently, I'm just testing it out with hard coded values. The ajax call to this url should be made when the submit button is clicked (which I also haven't implemented yet), but for now, I'm just testing to see whether or not the ajax call itself will work. Here is the form (I'm using crispy forms, so I didn't add the input fields manually):

<form method= 'POST' action = ''>{% csrf_token %}
{{ form|crispy }}

<input type= 'submit' value= 'Submit'>

and the ajax call:

$.ajax({
    dataType:'json',
    url: 'http://api.bandsintown.com/events/search?artists[]=foals&location=New York,NY&radius=150&format=json&app_id=YOUR_APP_ID',
    success: function(data){
        //console.log(data);
        concertData = data;
        runMainProgram();
        $(data.tickets).each(function(index, value){
                console.log(value.p);
        });
    }
})

Here is the form for the page from forms.py:

class SearchForm(forms.Form):
    artist_select = forms.CharField()
    city = forms.CharField()
    state = forms.CharField()

I thought that since I added the {% csrf_token %} that the wouldn't be an error with cross origin referencing, but when I load the page, I'm getting the error:

XMLHttpRequest cannot load http://api.bandsintown.com/events/search?artists[]=foals&location=New%20York,NY&radius=150&format=json&app_id=YOUR_APP_ID. No 'Access-Control-Allow-Origin' header is present on the requested resource.

I may be misinterpreting the error, but it seems like that is the problem. How should I go about fixing this issue?

loremIpsum1771
  • 2,497
  • 5
  • 40
  • 87

1 Answers1

0

You have the error because you don't send the csrf_token in your request header:

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');

$.ajax({
    headers: {'X-CSRFToken': csrftoken}, // you add you token here
    dataType:'json',
    url: 'http://api.bandsintown.com/events/search?artists[]=foals&location=New York,NY&radius=150&format=json&app_id=YOUR_APP_ID',
    success: function(data){
        //console.log(data);
        concertData = data;
        runMainProgram();
        $(data.tickets).each(function(index, value){
                console.log(value.p);
        });
    }
})

Check Ajax with Django

Dhia
  • 10,119
  • 11
  • 58
  • 69
  • Thanks for the answer! For some reason though, I'm getting the error: ```ReferenceError: jquery is not defined var cookie = jquery.trim(cookies[i]);``` is the jquery object supposed to automatically be defined once you load it from the CDN? Also, where did you get the code for getting the csrftoken from the cookie jar? I mean, how did you know to do that? – loremIpsum1771 Dec 13 '15 at 06:36
  • JavaScript is case sensitive, so it won't know `jquery` you should write `jQuery` as in the exmaple or simply `$`. It was mentioned in your error message that the header is missing. Check the post for the source. – Dhia Dec 13 '15 at 09:09
  • Ok, so it seems that all of the syntax errors have been fixed, but I'm now getting the warning: ```Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://api.bandsintown.com/events/search?artists[]=foals&location=New%20York,NY&radius=150&format=json&app_id=YOUR_APP_ID. (Reason: CORS header 'Access-Control-Allow-Origin' missing).``` I think I did everything right but maybe the problem has to do with the fact that I'm using Django [crispy forms](http://django-crispy-forms.readthedocs.org/en/latest/) – loremIpsum1771 Dec 13 '15 at 18:37
  • I don't think it have any thing with crispy forms, it seems like the problem is with the CROS header, check a solution I shared here [stackoverflow.com/5658350](http://stackoverflow.com/a/34213423/5658350), it should solve it. – Dhia Dec 14 '15 at 05:29
  • I just tried installing django cors headers and added the necessary information to the settings.py file but for some reason, I'm still getting that error.... – loremIpsum1771 Dec 15 '15 at 20:58
  • 1
    Check this http://stackoverflow.com/a/9627028/5658350, because all what you need to communicate with the server is the crsf and the cors header, otherwise it could be a conflict/wrong configuration somewhere. – Dhia Dec 15 '15 at 21:14
  • Yeah, actually it seems to have been an issue with the fact that the api isn't allowing the client to request the data, so I will have to do it in python on the server side. – loremIpsum1771 Dec 15 '15 at 21:37