title: Access-Control-Allow-Origin getJSON Rails
body: <p>I have some code that works fine in <strong>development</strong>.</p>
  
  <p><strong>ORIGINAL CODE</strong></p>
  
  <pre><code>respond_to :json
  
  def index
    @tags = current_user.tags
    respond_with(@tags.map{|tag| {:id =&gt; tag.id, :name =&gt; tag.name} })
  end
  </code></pre>
  
  <p>with a route file of</p>
  
  <pre><code>get "tags/index"
  </code></pre>
  
  <p>and my jQuery file has a line like this</p>
  
  <pre><code>$.getJSON('http://localhost:3000/tags.json', function(data) {
  </code></pre>
  
  <p>However, when pushing it to <strong>production</strong>  I get an error
  XmlHttpRequest error: Origin is not allowed by Access-Control-Allow-Origin. After doing some research </p>
  
  <p><a href="https://stackoverflow.com/questions/3828982/xmlhttprequest-cannot-load-an-url-with-jquery">Here</a>
  <a href="https://stackoverflow.com/questions/14120937/handling-jsonp-in-rails-3-controller">Here</a>
  and 
  <a href="http://www.tsheffler.com/blog/?p=428" rel="nofollow noreferrer">Here</a></p>
  
  <p>I changed my code to this</p>
  
  <p><strong>NEW CODE</strong></p>
  
  <pre><code>def index
    @tags = current_user.tags
    respond_to do |format|
      if params[:callback]
        format.json { render :json =&gt; @tags.map{|tag| {:id =&gt; tag.id, :name =&gt; tag.name}   }.to_json , :callback =&gt; params[:callback]}
      else
        format.json { render :json =&gt; @tags.map{|tag| {:id =&gt; tag.id, :name =&gt; tag.name} }}
      end
    end
  end
  </code></pre>
  
  <p>and</p>
  
  <pre><code>$.getJSON('http://localhost:3000/tags.json' + '&amp;callback=?', function(data) {
  </code></pre>
  
  <p>with the same route.</p>
  
  <p>What is going on here? I'm still getting the same error, why didn't the callback fix it?</p>
  
  <p><strong>all jQuery Code</strong></p>
  
  <pre><code>  var items = [];
    var prepopulate = [];
  
    $(function () {
       var myVarsJSON = $("#my_vars_json").html(),
            myVars     = $.parseJSON(myVarsJSON);
          $.each(myVars, function(i, obj) {
            return prepopulate.push(obj.name);
            });
  
      $.getJSON('/tags.json' + '&amp;callback=?', function(data) {
          $.each(data, function(i, obj) {
              return items.push(obj.name);
              });
       $("#article_tag_ids_edit").val(prepopulate).select2({
        width: "element",
        tags: items,
        tokenSeparators: [",", " "]
        });
      });
    });
  
    $.getJSON('/tags.json' + '&amp;callback=?', function(data) {
          $.each(data, function(i, obj) {
              return items.push(obj.name);
              });
  
        $("#article_tag_ids").select2({
        width: "element",
        tags: items,
        tokenSeparators: [",", " "]
      });
    });
  </code></pre>