Marko
Marko

Reputation: 41

Get length of text in div generated with ajax

I am having .php document with a lot of string in array. My page takes one of them and puts into empty div named post. When I want to get length of post its always :

Uncaught TypeError: Cannot read property 'length' of undefined

So I assume that my jQuery code reads <div class="post"></div> which is blank untill website loads and generates text into that. So how can i get lenght of generated string from my post.php document?

<html>
  <head>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script>
      function getPost()
      {
        $.ajax({
          type: 'POST',
          url: 'posts.php',
          dataType: 'html',
          cache: false,
          success: function(result) {
            $('.post').html(result);
          },
        });
      }
      getPost();
    </script>
  </head>
  <script>
    var postPoints = $(".post").val().length;
  </script>
  <body>
    <div class="post"></div>
  </body>
</html>

posts.php

<?php
    $posts = array(
      "string1",
      "string2",
      "string3",
      "string4"
    );

    $maxPosts = sizeof($posts);
    $generatePost = rand(0,$maxPosts);
    if($lastPost != $generatePost)
    {
      echo $posts[$generatePost];
      $lastPost = $generatePost;
    }
    else
    {
      $generatePost = rand(0,$maxPosts);
      echo $posts[$generatePost];
      $lastPost = $generatePost;
    }
?>

Upvotes: 1

Views: 410

Answers (2)

user7106955
user7106955

Reputation:

function getPost()
{
$.ajax({
        type: 'POST',
        url: 'posts.php',
        dataType: 'html',
        cache: false,
        success: function(result) {
            $('.post').html(result);
            var length = result.length; //for further uses, you may also assign this value with global variable.
        },
    });
}

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

First the script var postPoints = $(".post").val().length; can't find the post div at all that why you're getting undefined error message :

Uncaught TypeError: Cannot read property 'length' of undefined

And that because you're trying to get the div before the page is fully loaded (That could be fixed using ready function) :

$(function(){
    var postPoints = $(".post").val().length;
})

This way the script will find your div but it will always return '0'.

So you should get the length after getting the response of the ajax request, you've to put your line inside the success callback :

success: function(result) {
    $('.post').html(result);
    alert( $(".post").val().length );
},

Hope this helps.

Upvotes: 3

Related Questions