2
$.post('includes/script.php', $(this).serialize(), function(data) {
    $('body').append(data);
});

alert ($('#new').length)

php script is <php echo "<div id="new">text</div>" ?>

it alerts 0, so it can't see new div.

How can you make it see new div?

Qiao
  • 16,565
  • 29
  • 90
  • 117
  • my bad, too simplified it. corrected. – Qiao Mar 14 '10 at 01:42
  • found it. async: false. http://stackoverflow.com/questions/755885/how-do-i-make-jquery-wait-for-an-ajax-call-to-finish-before-it-returns – Qiao Mar 14 '10 at 02:26
  • 1
    @Quio if you can move your code in to the success handler it will work for you. Javascript is an event drivin language. – PetersenDidIt Mar 14 '10 at 02:39

2 Answers2

1

You have to wait till your post is done before you can check the length. Do something like this:

$.post('includes/script.php', $(this).serialize(), function(data) {
    var newItem = $(data).appendTo('body');
    alert (newItem.length);
});
PetersenDidIt
  • 25,562
  • 3
  • 67
  • 72
0

How are you calling it? I get alert 1 in Firefox, Chrome, and IE. Note that "function" was misspelled in your code snippet.

<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">

$(document).ready( function() {
addnew();
});

function addnew (){
    $('body').append('<div id="new">text</div>');
    alert ($('#new').length)
}
</script>
harpo
  • 41,820
  • 13
  • 96
  • 131