Question

I have a problem getting json data to display in a static website. the data comes from a simple ruby on rails REST service - which is located on heroku. in this example I am just using it from localhost. Right it says that my data is undefined.

$(document).ready(function() {

  $.ajax({  
    type: "GET",
    url: "http://localhost:3000/projects.json", 
    cache: false,
    dataType: "json",
    data: {
      success: function(data) { 
        alert(data);
        $.each(data, function(index, value) { 
          var v = JSON.parse(value);
          $("<ul><li>" + v.name + "</li><li>" + v.description + "</li><li>" +v.tech + "</li></ul>")
            .appendTo($("#tech"));
        });
      }
    }
  });

});  

my other question is how do I append it to the attributes name, description, tech - this in html:

<section id="projects">
        <h2>
            Projects
        </h2>
         <article id="project">
             <img id="project-image" src="" alt=""/>
            <label id="name">

             </label>
             <ul id="tech">
                <li>

                 </li>
                 <li>

                 </li>
             </ul>
             <p id="description">

             </p>
         </article>
Was it helpful?

Solution 2

added this in my projects_controller:

 def index
  @projects = Project.all
  projects = @projects.to_json
  respond_to do |format|
  format.json {render :json => projects, :callback => params[:callback]}
 end
end 

and on the client/ajax side:

$(document).ready(function() {

  $.ajax({  
    type: "GET",
    url: "heroku_url/projects.json", 
    cache: false,
    dataType: "json",
    success: function(data) { 
    alert(data);

    $.each(data, function(index, value) { 

    $("<article id='project'><label id='name'>"+data[index].name+"</label>
    <pid='tech'>"+data[index].tech+"</p><p id='description'>"+data[index].description+"
    </p></article><br />").appendTo($("#projects"));

     });
    }
  });
});    

OTHER TIPS

@BroiSatse is right - success should not be inside data. Try the following:

$(document).ready(function() {

  $.ajax({  
      type: "GET",
      url: "http://localhost:3000/projects.json", 
      cache: false,
      dataType: "json",
      success: function(data) { 
        alert(data);

        $.each(data, function(index, value) { 
          var v = JSON.parse(value);

          $("<ul><li>" + v.name + "</li><li>" + v.description + "</li><li>" +v.tech + "</li></ul>")
                                    .appendTo($("#tech"));
        });
      }
    });
 }); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top