Sunday, 26 July 2015

Create a textarea with word count using jQuery and PHP

Leave a Comment

First create a textarea and give it id and name. Add text “Word Count:” and a span tag with id “count” like shown below.

<textarea cols="20" rows="5" name="textarea" id="textarea"></textarea>
<br>Word count: <span id="count"></span>

Now we will write jQuery code so you need to add jQuery library.  We will use the keyup event in the jQuery to call function. So whenever key is released we will call anonymous function to execute the code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("#textarea").keyup(function(){

});
</script>

Here we are calling a function whenever we type a character in textarea ie., to count number of words typed in the textarea. Now whenever we type character in textarea we need to count number of words present in the textarea.


We have a built-in function in PHP to count the number of words. So now we should send the typed words to the PHP script and get the output. We can do this using jQuery ajax method.

$.ajax({
url: 'count.php',
type: "POST",
data: {textarea:$("#textarea").val()},
dataType :'html',
success: function(result){
$("#count").empty();
$("#count").append(result);

},
error: function(){
alert("Ahh! something went wrong. Please try again after sometime.");
}
});

In the above code we are sending the data typed in the textarea to count.php file. If success append it to span tag else alert a message. Let’s see the count.php file.

<?php
$str = $_POST['textarea'];
$count = str_word_count($str);
echo $count;
?>

Since we are sending values using post method we are using $_POST in php to store the value in variable. str_word_count will count the number of words in variable $str. Finally output is echoed.


Let’s see the final code.

<textarea cols="20" rows="5" name="textarea" id="textarea"></textarea>
<br>Word count: <span id="count"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("#textarea").keyup(function(){

$.ajax({
url: 'count.php',
type: "POST",
data: {textarea:$("#textarea").val()},
dataType :'html',
success: function(result){
$("#count").empty();
$("#count").append(result);
},
error: function(){
alert("Ahh! something went wrong. Please try again after sometime.");
}
});
</script>

0 comments:

Post a Comment

.