1

I'm trying to learn how to 'GET' data from my rails 3.2.2 project asynchronously. I am new to both javascript and jquery but I've learned, javascript cannot GET data from a server in a different domain. To get around that I've read about using $.ajax(), $getJSON(), and/or $.jsonp(), so my first question is when should you use one over another?

I'm trying to get one technique to work (e.g. $.ajax() within my rails 3.2.2 project. I have a simple scaffold consisting of one controller => Images and one field => t.string:name.

class ImagesController < ApplicationController
  # GET /images
  # GET /images.json
  def index
    @images = Image.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @images }
    end
  end

  # GET /images/1
  # GET /images/1.json 
  def show
    @image = Image.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @image }
    end
  end

  # GET /images/new
  # GET /images/new.json
  def new
    @image = Image.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @image }
    end
  end

  # GET /images/1/edit
  def edit
    @image = Image.find(params[:id])
  end

  # POST /images
  # POST /images.json
  def create
    @image = Image.new(params[:image])

    respond_to do |format|
      if @image.save
        format.html { redirect_to @image, notice: 'Image was successfully created.' }
        format.json { render json: @image, status: :created, location: @image }
      else
        format.html { render action: "new" }
        format.json { render json: @image.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /images/1
  # PUT /images/1.json
  def update
    @image = Image.find(params[:id])

    respond_to do |format|
      if @image.update_attributes(params[:image])
        format.html { redirect_to @image, notice: 'Image was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @image.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /images/1
  # DELETE /images/1.json
  def destroy
    @image = Image.find(params[:id])
    @image.destroy

    respond_to do |format|
      format.html { redirect_to images_url }
      format.json { head :no_content }
    end
  end
end

I first want to explore the index action and 'GET' a list of image names using an $.ajax() call in up.html:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">    </script>
</head>
<body>
    <script>
        $(document).ready( function (){ 
            $("button").click(function(){
                    $.ajax({
                        dataType: 'jsonp',
                        url: "http://localhost:3000/images",
                        success: function(response) {
                            console.log(response);
                        }
                    });
            });
        });
    </script>

    <button id ="button" type ="button">Get names</button>

</body>
</html>

I received the following from the console:

event.layerX and event.layerY are broken and deprecated in WebKit. They will be removed  from the engine in the near future.
jquery.min.js:16Resource interpreted as Script but transferred with MIME type text/html:  "http://localhost:3000/images?    callback=jQuery15209319186636712402_1334849479698&_=1334849481034".
images:1Uncaught SyntaxError: Unexpected token <

I'm lost here. I'm not sure if I should be using '?callback=?' in my url or if I should have additional parameters in my controller or something else entirely?

JohnGalt
  • 2,851
  • 2
  • 21
  • 29
  • regarding the first warning message you get in the console, see http://stackoverflow.com/questions/7825448/webkit-issues-with-event-layerx-and-event-layery – Matt Apr 19 '12 at 15:53

2 Answers2

2
       $(document).ready( function (){ 
            $("button").click(function(){
                    $.ajax({
                        dataType: 'json',  // not jsonp
                        url: "http://localhost:3000/images.json",
                        success: function(response) {
                            console.log(response);
                        }
                    });
            });
        });
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • after the change localhost:3000/images.json, the errors went away, however, I expected to see the records in the Images table, but nothing showed up in the console. – JohnGalt Apr 19 '12 at 16:11
  • XMLHttpRequest cannot load http://localhost:3000/images.json. Origin http://localhost is not allowed by Access-Control-Allow-Origin. – JohnGalt Apr 19 '12 at 16:17
  • removal of json as a datatype causes the cross domain issue and response doesn't have any values. – JohnGalt Apr 20 '12 at 00:10
1

Ignore the first line in your console - that's a standard warning that appeared in recent Chrome/jquery versions.

The second line is telling you that your web app sent html, rather than json

The third line is due to trying to parse html (presumably starting with "<html...") as if it were a json string.

So, you need to tell rails to send you json, not html. Try changing your url in the json call to ""http://localhost:3000/images.json".

Jonathan del Strother
  • 2,552
  • 19
  • 32
  • Thank you for the response. After the change http://localhost:3000/images.json, the errors went away, however, I expected to see the records in the Images table, but nothing showed up in the console. – JohnGalt Apr 19 '12 at 16:06