Mr Goobri
Mr Goobri

Reputation: 1469

Why is my alert not displaying the DIV I want it to display?

The following code sends an alert to the screen as 'undefined'. I would like to alert the html of #div.

    $.ajax({
        type: "POST",
        url: pageurl,
        dataType: "html",
        success: function(data){
            alert($(data).children("#div").html());
        }       
    });

I could do something like in load, but I don't think I'm allowed:

    url: pageurl + ' #div'

How can I resolve this?

UPDATE: Based on advice from @Murali, I've tried the following, but it still doesn't behave as I would like:

<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {  
    $.ajax({
            type: "POST",
            url: 'index.html',
            dataType: "html",
            success: function (data) {                    
                alert($(data).find('#site-content').html());
            }
        });
});
  </script>

<title></title>
</head>
<body>
<div id="site-content">
    some data</div>
</body>
</html>

Upvotes: 1

Views: 1354

Answers (2)

Murali Murugesan
Murali Murugesan

Reputation: 22619

Try

Change this

 $(data).children("#div").html()

To

 $(data).find('#yourDivId').html()

Note: yourDivId -> give the id of the div. In your code you mentioned as '#div' not sure whether really your code is like <div id='div'>

Code i tried

in Index.html

      $.ajax({
            type: "POST",
            url: 'page.html',
            dataType: "html",
            success: function (data) {                    
                $(data).find('#site-content').html();
            }
        });

In Page.html

 <head>
<title></title>
</head>
<body>
<div id="site-content">
    some data</div>
</body>
</html>

Upvotes: 2

Nasser Ghiasi
Nasser Ghiasi

Reputation: 372

are you sure

$(data).children("#div") 

return definded element? try this:

String($(data).children("#div").html());

or try

console.log($(data).children("#div").html());

for reassured returned data is string and not empty.

Upvotes: 0

Related Questions