skip to Main Content

I am very new to jQuery and AJAX so I apologise if I am being stupid.

I am receiving an error in my AJAX jQuery script.
I am retrieving data via AJAX get to display dynamically on my page.
The JSON file returns an array which must be iterated and displayed in a DIV for each item.
The JSON is:

[{"id":1,
"user_id":14,
"title":"The Title",
"thumbnail":"image.jpg",
"summary":"summary of post",
"content":"content info here",
"category":"Graphic Design",
"sub_category":"Adobe Photoshop",
"views":0,
"published":0,
"created_at":"2015-04-16 00:09:57",
"updated_at":"2015-04-16 00:09:57"}, {and so on...}]

The jQuery is:

function retrieveTutorials()
{
	$.ajax({
	    type: "GET",
	    url: "/tutorials/retrieve",
	    dataType: "json",
	    success: function(data){
          var tutorial = ('')
            $.each(data, function(){
            
                     tutorial.append($(  '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))
            });
            
          $("#generated-content").empty().append(tutorial);
            
		},
		error: function() {
			alert("An error occurred while processing XML file.");
		}
	});
}

The error I am currently receiving is “Uncaught TypeError: undefined is not a function” which refers to the following section

tutorial.append($(  '<div class="generatedbox"><img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p></div>'))

Any ideas as to where I am going wrong?
I have used very similar code before which worked fine

4

Answers


  1. try this

    var tutorial = $('<div></div>');
    
    Login or Signup to reply.
  2. You should select any DOM Element and assign it to tutorial variable, something like this:

    var tutorial = $('someCSSselector');
    
    Login or Signup to reply.
  3. You should define your div object first, and you can keep generatedbox class when defining it. Then, you can omit the div that you had in the appended content.

      var tutorial = $('<div class="generatedbox">')
      $.each(data, function(){            
            tutorial.append($('<img src="images/tutorial_upload/' + this.thumbnail + '" /><h1>' + this.title + '</h1><p>' + this.summary + '</p><p class="date">' + this.created_at + '</p>'))
      });
    
    Login or Signup to reply.
  4. There is an error because you are calling .append() on (''). .append() is a jQuery function, but ('') is an empty string, not a jQuery object.

    You can do this:

    var tutorial = $('<div>');
    ...
    $("#generated-content").empty().append(tutorial.html());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search