-2

I am using $.ajax to get content from a .php page which returns something similar to the following

<div class="item">
   <h1>Item Name</h1>
   <div class="content">
      <p>Content here</p>
   </div>
</div>

Here is my fetching code:

$.ajax(
{
   type: "GET",
   url: appletGet,
   data:
   {
      'name': this.name
    },
    success: function (data) 
    { 
       console.log(data.replace('\n', ''));
       $(element).append(data.replace('\n', ''));
    }
});

and I try to append it using

$(element).append(data);

but I get the error:

Uncaught SyntaxError: Unexpected token <

I look at some other posts and they all talked about the new lines causing the issue. Because of that, I attempted to remove new lines.

$(element).append(data.replace('\n', ''));

Which did not work. So, how do I go about fixing this?

Edit: Kepi gave an answer earlier which proposed that I use

$.parseHTML(data)

and then append that. He/She removed his/her answer due to second-guessing himself/herself. Since I do not think you can give credit when it is removed (I am correct right?) I am putting this solution here for future reference.

Kepi! Come get your credit!

UioShi
  • 21
  • 1
  • 7

1 Answers1

0

I don't see anything wrong here. Refer to this JSFiddle:

var data = '<div class="item">'+
   '<h1>Item Name</h1>'+
   '<div class="content">'+
      '<p>Content here</p>'+
   '</div>'+
'</div>';

$("body").append(data.replace("\n", ""));

Moreover if you are getting html response you may consider using $.load.

Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
Anupam Basak
  • 1,503
  • 11
  • 13