stackminu
stackminu

Reputation: 781

$.post returns [object Object]

Why this returns [object Object] ??? I want to return #new content in to a alert. (actually i want to append that text to a new div, I can do that if this [object Object] problem resolved)

<script type="text/javascript">
      $(document).ready(function() {
        $.post("post.php", {"test": "hello"}, function(data) {
           var myDiv = $(data).filter("#new");
           alert(myDiv);
        });
      });
</script>

Upvotes: 0

Views: 320

Answers (5)

tijs
tijs

Reputation: 566

myDiv will contain a jQuery object, so if you want to see its' contents, you shoud use

alert(myDiv.text());

or

alert(myDiv.html());

or

console.log(myDiv);

Upvotes: 0

Naftali
Naftali

Reputation: 146360

It works perfectly fine.

alert does not show all the properties of an object, which is what you are trying to alert.
Try using the console for that:

//info on the jQuery DOM obj:
console.log(myDiv);

//info on the jQuery obj:
console.dir(myDiv);

For example: http://jsfiddle.net/agNNW/ (Thanks @Esailija)

Upvotes: 3

nnnnnn
nnnnnn

Reputation: 150080

Like many jQuery methods, .filter() returns a jQuery object, so your current alert is quite correctly showing [object Object].

Assuming data is a string of html, you can see the contents of the #new element within that html by doing this:

var myDiv = $(data).filter("#new");
alert(myDiv.html());
// or
alert(myDiv.text());
// or put the text in a variable:
var newText = myDiv.html();
// or
var newText = $(data).filter("#new").html();

To append to your other element:

$("#someotherelement").append(myDiv.html());

Upvotes: 0

jbabey
jbabey

Reputation: 46657

I'm going to take a wild guess and say it is working perfectly. If your myDiv is a DOM element, that is an object and alert has no idea how to print it. Never rely on alert for debugging purposes. Try appending it to a DOM element and it will probably work fine.

Upvotes: 0

Adil
Adil

Reputation: 148180

Because myDiv is object you have to access html in it,

use html() function of jquery if you want html, use text() function of jquery if you want text instead of html

 myDiv.html();

   $(document).ready(function() {
    $.post("post.php", {"test": "hello"}, function(data) {
       var myDiv = $(data).filter("#new");
       alert(myDiv.html());
    });
  });

Upvotes: 1

Related Questions