Munchkin
Munchkin

Reputation: 1085

How to append an AJAX reply

I searched the site and surprisingly did not find any answers fitting my situation. So I posted this question.

I am using jQuery AJAX to fetch a web page and dynamically add it to the website. But my code does not work and throws an error ERROR TypeError: "data.append is not a function".

My code is:

 $.ajax({
      url: "http://localhost:3000/treeviewuser/testuser",
      beforeSend: function( xhr ) {
        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
      }
    })
      .done(function( data ) {
        if ( console && console.log ) {
          console.log( "Sample of data:", data.slice( 0, 100 ) );
          data.append(data);
        }
      });
  }); 

Upvotes: 1

Views: 426

Answers (2)

Dexter Bengil
Dexter Bengil

Reputation: 6625

You need to find the element where you want to append the response data. $("#my_div_id").append(data[0]) instead of data.append(data); If your data is an array or an array of objects, you'll need to loop through each of them when appending; else when the data you return from your ajax is in a type of text or html, you can just directly append it on your document. $("#my_div_id").append(data)

Upvotes: 1

Terry
Terry

Reputation: 66123

To further elabourate on my comment, data is the response returned from the endpoint, which does not have the .append() method. Based on your response, you intend to print the output to the document. There are two ways to do this:

1. Create a new element with the text, and append to document

If you do not have a target element on the page you want to append the data to, you can simply create a new element and set its inner text to the data returned from the server:

$.ajax({
    url: "http://localhost:3000/treeviewuser/testuser",
    beforeSend: function( xhr ) {
        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
    }
}).done(function( data ) {
    const el = document.createElement('div');
    el.innerText = data;

    document.appendChild(el);
});

If you're more comfortable writing in jQuery, you can also do this:

$.ajax({
    url: "http://localhost:3000/treeviewuser/testuser",
    beforeSend: function( xhr ) {
        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
    }
}).done(function( data ) {
    const $el = $('<div />', {
        text: data
    });

    $(document).append($el);
});

2. Append text to a pre-existing element

Let's say you have an element with the ID of output that you want to print the response to, i.e. <div id="output"></div>, then you can do this:

$.ajax({
    url: "http://localhost:3000/treeviewuser/testuser",
    beforeSend: function( xhr ) {
        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
    }
}).done(function( data ) {
    $('#output').text(data);
}); 

Upvotes: 3

Related Questions