JohnGalt
JohnGalt

Reputation: 2881

Obtaining data asynchronously using $.ajax() in rails 3.2.2

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?

Upvotes: 1

Views: 1222

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87073

       $(document).ready( function (){ 
            $("button").click(function(){
                    $.ajax({
                        dataType: 'json',  // not jsonp
                        url: "http://localhost:3000/images.json",
                        success: function(response) {
                            console.log(response);
                        }
                    });
            });
        });

Upvotes: 2

Jonathan del Strother
Jonathan del Strother

Reputation: 2572

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".

Upvotes: 1

Related Questions