user1885433
user1885433

Reputation:

parsing returned data in success function never works

$.ajax({
    type : 'GET',
    url : 'dialog.php',
    data: {
        champion_name:champion_name
    },
    dataType: "text",
    success : function(data){
        alert(data);
        var dataStr = $(data).find('h2').html();
        $('#champImg').find('div').html(dataStr);

    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
        alert('failed');
    }
});

I tried to parse returned data in success function because I need to append some elements in one certain div and other elements in other div.

However, $(data).find('h2').html() never works.
I tried every possible way including changing dataType to html, but it is working.

The returned data is valid because I see it alerts html codes from dialog.php successfully. Only $(data).find('h2').html() does not work!

Upvotes: 4

Views: 393

Answers (2)

Steve O
Steve O

Reputation: 5784

You could use the jQuery filter method instead of find:

var dataStr = $(data).filter("h2").html();

Here's an example jsFiddle: http://jsfiddle.net/5zWHa/

Upvotes: 1

Rune FS
Rune FS

Reputation: 21752

It fails because there's no outer element and the selection therefor returns two elements. Find searches then children of the current element but your selection returns two elements one for the image and one for the h2 neither with a h2-child

if the html had been

<div>
   <img class='style2' 
        border='2' 
        src='$imgPath' 
        style='width:165px;height:232px;'>   
   <h2>hello</h2>
</div>

it would work.

if you can't/won't change the returned html you can change the success handle to

function(data){
  alert(data);
  var dataStr = $(data)[1].html();
  $('#champImg').find('div').html(dataStr);
}

Upvotes: 3

Related Questions