Auto creating div's with jQuery and inserting data from mysql - php

I want to make auto creating div's with jQuery. I have to fill them with data from MySql database. The problem is that when I use foreach loop it doesn't want to echo data.
Here is my code for mysql:
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$row = mysqli_num_rows($result);
And here is my jQuery code:
$(document).ready(function(){
var count = 1;
for(i = <?php echo $row; ?>; i > 0; i--){
$("#main").prepend('<div id="first'+count+'"></div>');
count++;
}
count = 1;
for(i = <?php echo $row; ?>; i > 0; i--){
<?php
while($col = mysqli_fetch_assoc($result))
{
$cols[] = $col;
}
foreach($cols as $col){
?>
$("#first"+count+"").text("<?php echo $col['post']; ?>");
count++;
<?php } ?>
}
});
I've also checked in inspect element and everything seems ok, but it doesnt want to create div's.
And if I change this echo $col['post']; to some other text, it works.
Here is what I get in inspect element:
$(document).ready(function(){
var count = 1;
for(i = 3; i > 0; i--){
$("#main").prepend('<div id="first'+count+'"></div>');
count++;
}
count = 1;
for(i = 3; i > 0; i--){
$("#first"+count+"").text("text1");
count++;
$("#first"+count+"").text("text2");
count++;
$("#first"+count+"").text("text3");
count++;
}
});
Thank you for ideas!

I run your code in my workstation it works fine.
I can suggest you check for duplicate id of your new created div you can alter them in class may be its not conflict then.
Is #main div binded before the page load.
check for database is data insertion OK.
Its just some suggestion. If you can say some specific details about the scene, then i can provide you some specific suggestion.
Thanks

Related

Limiting rows of table and appending rows

In this code I am getting posts from database in table, table displays posts in three columns, now I want to add some jQuery to limit the number of rows and add a button which on clicking appends few rows to table I am not a professional programmer may be something like slice should be used to limit number of rows.
$sql = "SELECT * FROM posts";
$query = $db->prepare($sql);
$query->execute();
<table>
<tr>
<?php do { //horizontal looper?>
<td>
<div>id</div>
<div>title</div>
<div>body</div>
<div>date</div>
</td>
<?php
$row = $query->fetch(PDO::FETCH_ASSOC);
if (!isset($nested_List)) {
$nested_List= 1;
}
if (isset($row) && is_array($row) && $nested_List++%3==0) {
echo "</tr><tr>";
}
} while ($row); //end horizontal looper
?>
</table>
HTML
Create your table (You can also create dynamically)
<table id='posts'>
<tbody></tbody>
</table>
<button id='load-more-entries'>Load</button>
JavaScript
Create a variable for keeping track of what result you are on. What the index of the last result you grabbed.
Grab the elements by id. attach listener to button so when you click you load more results. Take a look at AJAX documentation. It is very simple and short.
var index = 0;
var load, table;
load = document.getElementById('load_more_entries'),
table = document.getElementById('posts');
load.addEventListener('click', function(e){
processAjaxRequest({
type: 'get',
url: "posts.php?index="+index,
success: function(xmlhttp){
var results = JSON.parse(xmlhttp.response);
for(var i = 0; i < results.length; ++i){
var row = table.insertRow();
var cell = row.insertCell(cell_index);
//increment index according to how many results you
grab so next time you grab the next results
index++;
}
},
error: function(xmlhttp){
//Handle error
}
});
});
/*
this function here it is a a wrapped AJAX
it will call php file below and run it. It will fetch the results
form database and return them to you in form of a string. You need
to parse it JSON.parse() to turn it into an array
*/
function processAjaxRequest(object){
var xmlhttp = new XMLHttpRequest() ||
new ActiveXObject('Microsoft.XMLHTTP');
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
if(xmlhttp.status === 200){
object.success(xmlhttp);
}else{
object.error(xmlhttp);
}
}
}
xmlhttp.open(object.type, object.url, true);
xmlhttp.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
xmlhttp.send(object.args);
};
PHP
This file is called by processAjaxResquest
$posts = array();
while($post = mysqli_fetch_assoc($sql)){
$posts[] = $post;
}
echo json_encode($posts);
?>
*NOTE I have not tested the code there maybe a couple of thing I may have left of. However, this should be enough to get you started. I got the same kind of answer when I had this question. Also, note that there is also more things you need to be aware of; like checking the variables inside PHP file are set before you do anything.

google chart - Assigning random colors to data

My code is:
['checkio','money'],
<?php while($row = mysql_fetch_array($que)){ ?>
['<?php echo $row['checkio']?>' , <?php echo $row['money']?>],
<?php } ?>
According to my sources I should use a loop.
The problem with using a loop is that it cannot specify a separate color..
Its result is:
['checkio','money']
['in',1000]
['out',200]
all the data are the same color.
So, What should I do?
Not sure which chart are you using, but if you are drawing the chart with javascript, you can set a series color in the options of the chart. Here is an example:
var options = {};
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
options.series={};
for(var i = 0;i < data.getNumberOfRows();i++){
options.series[i]={color:getRandomColor()}
}
Full example: http://jsfiddle.net/z2ewqoe1/

Automatically updating chatbox

So i'm working on a javascript/php chatbox. Everything works except for it updating the contents of my div (this works once, but after that it doesn't keep updating it when a new message has been put into the database). Here is my code:
Javascript part:
<script language=javascript type='text/javascript'>
setInterval(function () {
var arrayOfObjects = <?print_r(getChatArray());?>;
var chat = "";
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
chat += "["+object.date+"]"+object.op+": " + object.msg + "</br>";
}
$('#chat').html(chat);
}, 10);
</script>
Php part:
<?php
function getChatArray() {
$result = mysql_query("SELECT * FROM shouts ORDER BY id DESC");
$to_encode = array();
$count = mysql_num_rows($result);
$size = 0;
if($count > 0) {
while($row = mysql_fetch_assoc($result)) {
$to_encode[$size]['id'] = $row['id'];
$to_encode[$size]['msg'] = $row['msg'];
$to_encode[$size]['op'] = $row['op'];
$to_encode[$size]['date'] = $row['date'];
$size += 1;
}
} else {
return "None";
}
return json_encode($to_encode);
}
?>
Any ideas as to why it isn't continually updating it?
Thanks.
Because every 10 milliseconds your JS is parsing the original chat room contents, you're not fetching any new contents. You'll need to implement an ajax call, and I'd highly recommend changing that setInterval to a recursive setTimeout with a more realistic delay of say 500ms so you don't kill the client.
Instead of this:
setInterval(function() {
var arrayOfObjects = <?print_r(getChatArray());?>;
...
You would use something like this:
(function updateChat(){
var arrayOfObjects,
chat,
max,
_object,
i = 0;
$.ajax({
url : '/getChatArray.php', // php echoes the json
success: function(arrayOfObjects){
for (max = arrayOfObjects.length; i < max; i++) {
_object = arrayOfObjects[i];
chat += "["+_object.date+"]"+_object.op+": " + _object.msg + "</br>";
}
$('#chat').html(chat);
setTimeout(updateChat, 500);
}
});
}());
Obviously you would populate that ajax handler to your needs, add some more params like dataType, etc, and some error handling.
Your database contents will only be output to the page on initial navigation to it.
This code:
var arrayOfObjects = <?print_r(getChatArray());?>;
Will only output the contents of getChatArray()'s return when PHP renders the page. So the script can only see one state of that functions return at the time of rendering.
You need to use AJAX to retrieve the content from your database asynchronously.
I suggest you:
Create a PHP script which outputs your data in JSON format
Use jQuery, specifically the getJSON function to retrieve that script's output
Do what you want to do with that data.

Google Maps API 3 - extracting markers from MySQL DB using PHP

<?
$query = mysql_query("SELECT * FROM poi_example");
while ($row = mysql_fetch_array($query)){
$name=$row['name'];
$lat=$row['lat'];
$lon=$row['lon'];
$desc=$row['desc'];
echo ("addMarker($lat, $lon,'<b>$name</b><br/>$desc');\n");
}
?>
this code (echo) shows the table data in HTML source code.. is there another way (which does not shows the data) to extract markers from table?
thank you.
tutorial & demo page
I prefer to render them as a JSON. You can either do that in-page as you have done above.
<?php
// do database connection here
// run query to fetch your results
$rows = array();
while ($row = mysql_fetch_array($query)) {
$rows[] = $row;
}
echo "<script>var items = '".json_encode($rows)."';</script>";
You can iterate over your items array in JavaScript.
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon, '<b>' + item.name + '</b><br />' + item.desc);
})(items[i]);
}
I presume your addMarker() function creates a standard Google Map marker.
Alternative, you can have a PHP script that fetches your items from the database as echoes them as a JSON string, and then just call that via AJAX with jQuery.
So your PHP script would simply be:
<?php
header('Content-Type: application/json');
// connect to database
// do query
$rows = array();
while ($row = mysql_fetch_array($res)) {
$rows[] = $row;
}
echo json_encode($rows);
exit;
And then in your JavaScript file:
$.getJSON('script.php', function(items) {
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon, '<b>' + item.name + '</b><br />' + item.desc);
})(items[i]);
}
});
Hope this helps.

cannot click items echoed by another page using ajax - $(document).on is not working

updated
i'm having 2 pages. An index page connected to a js file. This js file containing ajax code fetching data from database.
this is my js file
$(document).ready(function() {
// getting links from db andshow sub_menu div //
$(".menu_item").mouseover(function(){
$(this).addClass("selected").children().slideDown(500,function(){
var id = $(".selected").attr("id");
var ajax= false;
ajax = new XMLHttpRequest();
var qst = "?id="+id;
ajax.open("GET","ajax/get_sub_cats.php"+qst);
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
$(".sub_menu[title="+id+"]").html(ajax.responseText);
}
}
ajax.send(null);
});
});
// hiding sub_menu div //
$(".menu_item").mouseout(function(){
$(this).removeClass("selected").children(".sub_menu").slideUp(500);
});
// keeping sub_menu div visible on mouse over //
$(".sub_menu").mouseover(function() {
$(this).stop();
});
// clicking sub menu link in the menu //
$(document).delegate("a#subCatLink","click",function(){
alert("test");
});
// document ready end
});
and this is get_sub_cats php file used to fetch links from db
<?php
require('../_req/base.php');
$id = $_REQUEST['id'];
$getSubcatsQ = "select * from sub_cats where Main_Cat_ID = '$id'";
$getSubcatsR = mysql_query($getSubcatsQ);
$numrows = mysql_num_rows($getSubcatsR);
while($row = mysql_fetch_array($getSubcatsR)){
?>
<a id="subCatLink" href="products.php?id=<?php echo $row['Sub_Cat_ID']; ?>"><?php echo $row['Sub_Cat_Name']; ?></a><br />
<?php
}
mysql_close($connect);
?>
clicking links coming from the other php file using ajax is not working at all
Sorry, maybe this will help, maybe not. But...
Why don't you use something like this:
jQuery
$(".menu_item").mouseover(function(){
var id = $(".selected").attr("id");
var qst = "?id="+id;
var html = '';
$.getJSON('ajax/get_sub_cats.php'+qst, function(data){
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<a id="subCatLink'+data[i].Sub_Cat_ID+'" href="products.php?id='+data[i].Sub_Cat_ID+'">'+data[i].Sub_Cat_Name+'</a>';
}
$(".sub_menu[id="+id+"]").html(html);
});
});
PHP
require('../_req/base.php');
$return = array();
$id = $_REQUEST['id'];
$sql = "select * from sub_cats where Main_Cat_ID = '$id'";
$result = mysql_query($sql);
while($ln = mysql_fetch_array($result)){
$return[] = $ln;
}
echo json_encode($return);
ok try this
$(document).delegate("click","a",function(){
var target = $(this).attr("href");
alert(target);
});
That should, as a test, show the href for every link on your page. If that works, put all the links you want to show in a div. Then call it with
$('#divID').delegate("click","a",function(){
var target = $(this).attr("href");
alert(target);
})

Categories