Sometimes you want to read the database values in JavaScript.This article describes the real-time display of JavaScript Ticker using Database Values. Here is the one demo for testimonials(or any value) coming from databases which are display vertical ticker with the use of JavaScript.
Before we see how that demo works let’s check how we create this demo.
First of all, Create the Database Table and take fields you require if you don’t have a table yet.Use the following syntax to create the table.
After creating a table, create one page ticker.php and add the following script in Head tag as we are using script it is better to add code in Head Tag or you can add anywhere in Page as per your requirement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | <script type="text/javascript"> <?php $conn = mysql_connect("localhost","username","password"); $db = mysql_select_db("ticker_demo"); $res = mysql_query($qry); ?> var val= []; <?php $i=0; while($line = mysql_fetch_assoc($res)) { ?> val[<?php echo $i?>] = ' <table border="0" style="border:1px solid #362a47;" width=200px> <tr> <td valign="top"> <img src="images/<?php echo $line['image'];?>" width="60" height="60" onError="this.src=images/no_image.jpg"> </td> <td><?php echo $line['text_short'];?></b> </td> </tr> </table>'; // Place your data display within a ticker. <?php $i++; } ?> { document.getElementById('demo').innerHTML =val[j]; j++; if(j==4){ // Here i have apply fix value, you can change it with db value also j=0; } } </script> |
Above Code will do MySQL connection and fetch the data from the database and loop the data and using that data display as ticker.Here I am adding all html content to the global variable as an array and for ticker display, using array value one by one. After adding above code in the head tag, Add below line in Body.
1 2 3 | <div id="demo" style="display:inline"></div> |
Your Ticker will be displayed within this div tag so if you change its id, change it an element in the script also.You also like to read about Lazy Load Plugin for jQuery.
That’s it and your ticker is ready and checks your ticker on the frontend.
Have a look at the working demo here Ticker for DB values.
Hope this small look at “Database value Ticker” has been helpful, or even introduced javascript demo to you for the first time, so you enjoyed it.
Comments (1)