I want to be updating the divs with posts comments only when new comment is added to MySQL database.
Each of the div have a unique id for posts.
Here what i have but this only update one div leaving the rest empty
Any help is appreciated.
I have 3 php files
Bed.php (index page).
Bed2.php (display last comment time, if changes update with new data from bed1.php)
Bed1.php (post comment from data base for each post id)
<div class="commcommmpost1" idss="1" id="gantt1">comment from post with id 1</div>
<div class="commcommmpost1" idss="2" id="gantt2">comment from post with id 2</div>
<div class="commcommmpost1" idss="3" id="gantt3">comment from post with id 3</div>
<div class="commcommmpost1" idss="4" id="gantt4">comment from post with id 4</div>
<script>
$i = "1";
var auto_refresh = setInterval(function() {
$('.commcommmpost1').each(function(index,
el) {
var thisIDs = $(this).attr('idss');
$.get("bed2.php?id=" +thisIDs, function(data) {
//condition of data
if (data != $i) {
$('#gantt' +thisIDs).load('bed1.php?id=' +thisIDs).fadeIn("slow");
// alert(thisIDs);
$i = data;
}
});
});
}, 2000);
</script>
Related
I've got really ambitious problem today as I want to achieve something ridiculously stupid but satisfying.
Basically, I do have a database with data for gym exercises
CREATE TABLE IF NOT EXISTS `gp_progs` (
`prog_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`exer` varchar(250) NOT NULL,
`pic` varchar(15) NOT NULL,
PRIMARY KEY (`prog_id`),
UNIQUE KEY `prog_id` (`prog_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
--
-- Dumping data for table `gp_progs`
--
INSERT INTO `gp_progs` (`prog_id`, `name`, `exer`, `pic`) VALUES
(1, 'ABS', 'TO DO ABS YOU NEED TO DO THIS AND THAT', 'abs.jpg'),
(3, 'Arms2', 'this is what we want', 'abs.jpg'),
(7, 'Biceps', 'curls', 'abs.jpg');
I have treated it after digging the code for many hours with this code in PHP
$jsondb = "data/prog.json";
$q = "SELECT * FROM gp_progs";
$r = #mysqli_query ($dbc, $q);
/*$json = array();
while ($row = mysqli_fetch_assoc($r)){
$json[] = $row;
}
$jsondata = json_encode($json, JSON_PRETTY_PRINT);
if(file_put_contents($jsondb, $jsondata)) {
echo 'Data successfully saved';
}
It gave me a json file from which I realy want to build AJAX functional app like this one.
JS:
$(function() { // When the DOM is ready
var times; // Declare global variable
$.ajax({
beforeSend: function(xhr) { // Before requesting data
if (xhr.overrideMimeType) { // If supported
xhr.overrideMimeType("application/json"); // set MIME to prevent errors
}
}
});
// FUNCTION THAT COLLECTS DATA FROM THE JSON FILE
function loadTimetable() { // Declare function
$.getJSON('data/events.json') // Try to collect JSON data
.done( function(data){ // If successful
times = data; // Store it in a variable
}).fail( function() { // If a problem: show message
$('#event').html('Sorry! We could not load the timetable at the moment');
});
}
loadTimetable(); // Call the function
// CLICK ON THE EVENT TO LOAD A TIMETABLE
$('#content').on('click', '#event a', function(e) { // User clicks on event
e.preventDefault(); // Prevent loading page
var loc = this.id.toUpperCase(); // Get value of id attr
var newContent = ''; // Build up timetable by
for (var i = 0; i < times[loc].length; i++) { // looping through events
newContent += '<li><span class="time">' + times[loc][i].time + '</span>';
newContent += '<a href="data/descriptions.html#';
newContent += times[loc][i].title.replace(/ /g, '-') + '">';
newContent += times[loc][i].title + '</a></li>';
}
$('#sessions').html('<ul>' + newContent + '</ul>'); // Display times on page
$('#event a.current').removeClass('current'); // Update selected item
$(this).addClass('current');
$('#details').text(''); // Clear third column
});
// CLICK ON A SESSION TO LOAD THE DESCRIPTION
$('#content').on('click', '#sessions li a', function(e) { // Click on session
e.preventDefault(); // Prevent loading
var fragment = this.href; // Title is in href
fragment = fragment.replace('#', ' #'); // Add space after#
$('#details').load(fragment); // To load info
$('#sessions a.current').removeClass('current'); // Update selected
$(this).addClass('current');
});
// CLICK ON PRIMARY NAVIGATION
$('nav a').on('click', function(e) { // Click on nav
e.preventDefault(); // Prevent loading
var url = this.href; // Get URL to load
$('nav a.current').removeClass('current'); // Update nav
$(this).addClass('current');
$('#container').remove(); // Remove old part
$('#content').load(url + ' #container').hide().fadeIn('slow'); // Add new
});
});
HTML:
<section id="content">
<div id="container">
<h2>Upcoming Events in Yorkshire</h2>
<div class="third">
<div id="event">
<a id="sh" href="sh.html"><img src="img/sheffield.fw.png" alt="Sheffield, South Yorkshire" />Sheffield</a>
<a id="hu" href="hu.html"><img src="img/hull.fw.png" alt="Hull, East Yorkshire" />Hull</a>
<a id="ls" href="ls.html"><img src="img/leeds.fw.png" alt="Leeds, West Yorkshire" />Leeds</a>
<a id="yk" href="yk.html"><img src="img/york.fw.png" alt="York, West Yorkshire" />York</a>
</div>
</div>
<div class="third">
<div id="sessions">
<p>Select an event from the left</p>
</div>
</div>
<div class="third">
<div id="details"></div>
</div>
</div><!-- #container -->
</section><!-- #content -->
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/events.js"></script>
So the result I want to see is to click on the group of exercises e.g. Arms, which will open next exercises e.g. Biceps and then onclick I want to see programme with pictures. But I cannot find out how to change JS so it will give me what I want. Spent on it already 13 hrs and still cannot find anything online.
If something is not clear please let me know as I am still learning how to use overflow.
Thanks in advance!
This is for PHP website with an use of JS, MySQL, Google API and HTML of course.
Edit:
If it was not too clear, I want to get MySQL data to JSON (which I have done already)
[
{
"prog_id": "1",
"catg": "chest",
"name": "Chest",
"exer": "Three exercises per muscle group. Chest: Bench Press (3 sets of 10), Chest cable fly(3 sets of 10) and dumbbell fly (3 sets of 10)",
"pic": "abs.jpg"
}
]
And now I want to use it in AJAX in way of: on page I want to see Groups - 'catg' which on click will open list next to group on the same page with Muscle to train 'name' which afterwards open last list next to previous also on the same page showing Descirption 'exer' and Picture/s 'pic'. Just like in the picture below:
I think your problem is that you don't know how to get data from MySQL to JSON in PHP, then get that JSON into Javascript in a form that lets you manipulate it easily.
Here's how I do it. The key here is the use of str_replace.
PHP, using my own SQL() function to retrieve the result set via fetch_all(MYSQLI_ASSOC):
$subcategorydata =
SQL("select * from subcategoryoptions order by category, subcategoryoption");
$subcategories =
str_replace('\\"','\\\\"',
str_replace("'","\'",
json_encode($subcategorydata)));
Javascript (direct rather than via ajax in my case):
var subcategories = '<?php echo $subcategories; ?>';
var jsonSubcategories = JSON.parse(subcategories);
for (var row in jsonSubcategories) { ....
EDIT: Additional code to load 2 layers, toggling the display of the lower level on/off according to user clicks. This version assumes you've pulled all the data out of MySQL in one go (I've just hard-coded it) - you would probably want to use ajax to load stuff dynamically in practice - and my code is definitely not optimal, but it should do the job.
Main div into which the data is loaded is followed by the javascript to load it. Note the hide(), show(), toggle() and set() functions and the onclick.
<div id=main></div>
<script>
function set(div, value) {
document.getElementById(div).innerHTML = value;
}
function hide(div) {
var x = document.getElementById(div);
x.style.display = "none";
}
function show(div) {
var x = document.getElementById(div);
x.style.display = "block";
}
function toggle(div) {
var x = document.getElementById(div);
if (x.style.display === "none") { show(div); } else { hide(div); }
}
var json='[{"heading":"This is the first heading","detail":"This is the first detail"},{"heading":"This is the second heading","detail":"This is the second detail"}]';
var jsonData = JSON.parse(json);
var html = '';
for (var row in jsonData)
{
html += '<div id=hdr' + row + ' onclick=toggle(\'dtl' + row + '\')>';
html += '<b>' + jsonData[row].heading + '</b></div>';
html += '<div id=dtl' + row + '>' + jsonData[row].detail + '</div>';
}
set('main','Click on the headings to toggle the detail<br>' + html);
for (var row in jsonData)
{
hide('dtl' + row);
}
</script>
you have the name of the image already in the records and you should also know, were on the server the images can be found.
You can combine this knowledge and forge a URI from path and filename
I have a div that slides in when triggered with:
<a href="javascript:void(0)" id="'. $row['post_id'] .'" onclick="chatWith(id)">
using jquery:
function chatWith(postid){
$("#chat_window").slideToggle("up");
$(".chat_postid").text(postid);
}
<div id="chat_window">
<span class="chat_postid"><?php echo $_POST['id']; ?></span>
</div>
I want a new chat dedicated for that item to pop up
Any help is appreciated!
$(document).ready(function() {
$('a').click(function() {
var user_id = $(this).attr('id');
$("#chats").append('<div class="chat_window" id="chat_' + user_id +'">Chat window for id: '+ user_id +'</div>');
$("#chat_"+user_id).slideToggle("up");
});
});
Edit: To add the new div per each id you need to add div which will contain all the divs.
<div id="chats"></div>
Then instead of id chat_window make it as a class. Then copy my update javascript code from above.
Edit2: You just need to replace your chatWitch() function with this one:
function chatWith(postid){
$("#chat_window").append('<span class="chat_postid" id="chat_' + postid+'">Chat window for id: '+ postid+'</span>');
$("#chat_"+postid).slideToggle("up");
}
Try with bellow code
Text
$('a.chat_window').click(function()
{
var id = $(this).attr('data-id');
alert(id);
});
what i'm trying to do is check div value one by one via jquery and php, if php is say value is 1 to make the div value color red if its 0 to make the txt color blue, the check script is not working right if i put on php q1 = Tag1 is not making that div red color ...
This is my HTML:
<div class="Tags_Data">
<div class="TagID_1">Tag1</div>
<div class="TagID_1_Status"></div>
<div class="TagID_2">Tag2</div>
<div class="TagID_2_Status"></div>
<div class="TagID_3">Tag3</div>
<div class="TagID_3_Status"></div>
<div class="TagID_4">Tag4</div>
<div class="TagID_4_Status"></div>
<div class="TagID_5">Tag5</div>
<div class="TagID_5_Status"></div>
<div class="TagID_6">Tag6</div>
<div class="TagID_6_Status"></div>
</div>
This is my jquery script
$(document).ready(function() {
var delay = 200;
$("div[class*='TagID_']").each(function() {
$(this).hide().delay(delay).fadeIn(1850);
delay += 200;
var Tag_ID = $(this).attr("class");
var ID_Split = Tag_ID.split('_');
var Tag_Data_ID = ID_Split[2];
var Tag_Scan = $('.TagID_' + Tag_Data_ID);
// ----------------- Post Tag And Check It
$.post("tags_check.php", { q1 : Tag_Scan.attr("value") },
// ----------------- Get The Result
function(result) {
if(result == 1) {
Tag_Scan.css('color','red');
} else {
Tag_Scan.css('color','blue');
}
});
});
});
This is my PHP Code on tags_check.php:
<?php
if($_GET["q1"] == "Tag3") {
echo 1;
} else {
echo 0;
}
?>
Here is my code: http://jsfiddle.net/3C2Pa/1/
Update:
i update the script http://jsfiddle.net/3C2Pa/3 but still the checking is not working ... hope someone can help me with this
You've got three errors in your code:
First one:
var Tag_Data_ID = ID_Split[2];
arrays start from zero as index. So you'll find what you get in the position 1.
var Tag_Data_ID = ID_Split[1];
Second one:
Tag_Scan.attr("value")
you have to use
Tag_Scan.text();
Third one:
you are using "post" to call your php script but you are reading vals through "GET". Use $_POST or $_REQUEST
Moreover I suggest that you use id and class in a better way :)
This is my tree view
I have already done that when i do right click tree name(For example ,Asset, Non Current , Shah) and click add head Then there will come jquery dialog form and I add head code and head name and it is saved successfully in mysql database using codeigniter frame work in php.
Basically , it is created subhead under head.
I need when after submitting, it will be display subhead under that head without refresh tree. For Example ,
If i create subhead under asset then append subhead after "104-Kamrul" without refresh and Display without Change.
How can i solve it, Please any suggestions?
i think you need ajax to make what you need, just use a specific class for each tree parent for example:
<div class="parent-1">
<div class="child-1"></div>
<div class="child-2"></div>
</div>
<div class="parent-2">
<div class="child-1"></div>
<div class="child-2"></div>
</div>
now just load what you need following parents classess:
$('.parent-1').children('.child-1').load('http://site.com/url/to/load/new/childs');
or
var _childs = $.get('http://site.com/url/to/get/some/childs');
$('.parent-1').append(_childs);
Given the following markup:
<div id="tree">
<ul>
<li>Asset
<ul>
<li>101-Non Current</li>
<li>102-Current Asset</li>
<li>103-Abdul Halim Shah
<ul>
<li>10301-Shah
<ul>
<li>1030101</li>
</ul>
</li>
</ul>
</li>
<li>104-Kamrul</li>
</ul>
</li>
<li>2-Expenses</li>
</ul>
</div>
I wrote a couple of jQuery functions to dynamically add new nodes. One adds the node below the selector specified and the other adds it as a sibling:
function addSibling(selector, content) {
var markup = '<li>' + content + '</li>';
$(selector).parent().append(markup);
}
function addChild(selector, content){
var obj = $(selector);
var markup='<li>' + content + '</li>';
var element;
if ($('ul', selector).length > 0){
//nested list
element = obj.find('> ul');
} else {
element = obj;
markup = '<ul>' + markup + '</ul>';
}
element.append(markup);
}
Although you'll have to adapt them to your code, you can use the following click function to test them:
$("#tree ul").click(function (e) {
//addSibling(e.target, 'new one');
addChild(e.target, 'new one');
e.stopPropagation();
});
I didn't understand what your variable were, but to get the data to the server without a page load, you can use an ajax function something like the following:
$('#form').submit(function() {
var headCode = $('input[name="headCode"]').val();
var headName = $('input[name="headName"]').val();
$.ajax({
url: "load.php",
type: 'POST',
data: {
head_code: headCode,
head_name: headName
},
cache: false,
success: function(json){
alert('loaded');
}
});
return false;
});
I'm trying to remove a row from the accordion in JQuery then update my db with the removal. So far the removal of the row in the accordion works fine. I am then trying to get the index of the removed row and post it back to the same page so that it can run a MySQL query to remove the row in the db and then reload the accordion from the db now that the row has been removed.
My JavaScript is limited so I don't think I'm passing the index properly?
Thanks for the help.
<?PHP
if(isset($_POST['id'])){
$id = intval($_POST['id']);
mysql_query("DELETE FROM `$db_name`.`$tbl_3` WHERE id='$id'");
unset($_POST['id']);
header("Location: ".$siteurl."messenger.php");
}
?>
<SCRIPT>
$(function(){
$( "#inbox" ).accordion({
collapsible: true,
icons: { "header": "ui-icon-plus", "headerSelected": "ui-icon-minus" },
active: false
});
$('#myClicker').click(function() {
var parent = $(this).closest('DIV');
var head = parent.prev('DIV');
parent.add(head).fadeOut('slow',function(){$(this).remove();});
var index = jQuery(this).find("H4").index(ui.newHeader[0]);
$.post('messenger.php', { id: index }, function(data) {});
});
});
</SCRIPT>
This is how I'm displaying the data from the db.
<DIV id="inbox">
<?PHP
$sql="SELECT * FROM `$tbl_3` ORDER BY id DESC";
$result = mysql_query($sql);
while ($row=mysql_fetch_row($result))
{
?>
<DIV>
<H4><?PHP echo "".$row[3]."";?></H4>
</DIV>
<DIV>
<P><?PHP echo "".$row[4]."";?></P>
<INPUT type="button" id="myClicker" value="delete"/>
</DIV>
<?PHP
}
?>
</DIV>
I use a totally different method for these kind of things.
What I do is make a php function/file that compiles the accordeon, menu, table, div for me, when I need it updated I simple reload the contents of the container div with an ajax call to the generator.
That way I take all the guesswork out of it, and only need to pass one value to the php script. This script could then also do the database stuff.
try this
$('#myClicker').click(function() {
var parent = $(this).closest('DIV');
var head = parent.prev('DIV');
var index = parent.prev('DIV').find("H4").index(ui.newHeader[0]);
parent.add(head).fadeOut('slow',function(){$(this).remove();});
$.post('messenger.php', { id: index }, function(data) {});
});
});