0

I'm trying to extract the body tag from .ajax() but I get undefined logged to console...

This is my code:

$(document).ready(function(){
  var user;
  $(".subacc_info").on('click', '#submit_user_delete', function(){
    user = $(this).closest($(".subacc_info")).find($("#subacc_name")).text();
    $.ajax({
      type: "POST",
      url: '/user/profile/delete',
      data: {user: user},
      dataType: "html",
      success: function(data){
        $result = $(data).find('body').html();
        console.log($result);
      }
    });
  });

Am I doing something wrong?

console.log(data) prints this string to console:

'<!DOCTYPE html>
<html lang="en">
  <head>
    ...
  </head>

  <body>
    <div class="container">

       ....

    </div> <!-- /container -->
  </body>
</html>'
Valip
  • 4,440
  • 19
  • 79
  • 150

2 Answers2

0

It seems like Jquery is ignoring the <body> and <html> elements, so you're actually getting an array of what's contained in the body. A way to get around this is to append that HTML to another element and get the HTML of that element.

You can do so like bellow:

var data = '<!DOCTYPE html><html lang="en"><head></head><body><div class="container"></div> <!-- /container --></body></html>';

var temp = $('<div>').append($.parseHTML(data));

console.log(temp.html())
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
George
  • 6,630
  • 2
  • 29
  • 36
  • If the response html contain some data in `` tag, for example: `` The content in head tag will be also visible. – vee Oct 30 '18 at 02:18
-1

Ajax call is to load the json data,html files,images,jsp. First you should be knowing what object you gona get from ajax call.

There should be some div in calling page of ajax call where you can display the return output from ajax call.

$(document).ready(function(){
  var user;
  $(".subacc_info").on('click', '#submit_user_delete', function(){
    user = $(this).closest($(".subacc_info")).find($("#subacc_name")).text();
    $.ajax({
      type: "POST",
      url: '/user/profile/delete',
      data: {user: user},
      dataType: "html",
      success: function(data){
        $("#SomeDIVId").html(data);
      }
    });
  });