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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

7 Comments

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?
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.
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
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, it should solve it.
Check this 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.
|

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.