jQuery updateing multiple #divs, one mysql_query - php

A bit complicated, but ill do my best to explain my question.
I have a main file, dashboard.html.
Within that I have a jQuery function to load the mysql_query every 15sec to get the 15 or so variables that I need. (This is a financial/sales webapp...the sales agents want near realtime updates of the sales, orders, $earned..etc) which are displayed in a #div with multiple listitems contained within. No issues with this with the approach that every 15sec, query, then entire div is updated all at once. Because of this I have not attached an Jquery effect (namely fadeIn/fadeOut) to it, as then the entire div is constantly fading. Not the visual effect I would like, but as it stands, it works.
My Goal: To be able to do the mysql_query every 15sec. Grab the variables (which Im already doing currently. But now, I would like to be able to update ONLY the ListItem that has changed and attach the fade effect to just that item, not the entire #div as a whole.
What Im trying to avoid is separating out the query to 15 separate querys, as that obviously that is not efficient.
Hopefully that makes some sense to everyone. Code can be provided, but I dont think it will help at this point .. I need to understand what approach I need to go to develop the correct code. Thanks everyone for your anticipated help.
EDIT: Im adding a bit of code to help clarify where I stand:
dashboard.html
var auto_refresh = setInterval(function (){
$('#order_jq').load('stats_count.php')
}, 15000); // refresh every 15 seconds
and then in the body:
<div class="span8">
<div id="order_jq" class="centerContent">
Patiently loading stats ...
</div><!-- End id="ortder_jq -->
</div><!-- End .span8 -->
stats_count.php consists of (stripped down for clarity)
<?php
require "database/connect2.php";
$result = mysql_query( "SELECT .... NORMAL QUERY...NOTHING FANCY HERE")
while ($row = mysql_fetch_array($result))
{$orders = number_format($row['ordercount']);
$annual_order = number_format($row['annual_order']);
}
and lastly contained within stats_count.php I also include the list items:
<ul class="bigBtnIcon">
<li>
<a href="#">
<span class="icon entypo-icon-phone"></span>
<span class="txt">Orders</span>
<span class="notification"><?php echo $orders?></span>
</a>
</li>
<li>
<a href="#">
<span class="icon brocco-icon-mic"></span>
<span class="txt">Auburn</span>
<span class="notification blue"><?php echo $annual_order ?></span>
</a>
</li>
</ul>
-D

If you have multiple divs to be updated, you have to select them with their class ".class" not id "#id"..
To create mysql_query every 15 seconds, you need to make setInterval(function(),15000) where function must make ajax request to some page where to do this query..
I can advice you to use jQuery Ajax for those requests..

Without knowing more details about what format your data is being returned in its difficult to get into specifics but the general approach would be:
store current values into an object,
create a new object with your incoming values
cycle through the properties of the obect comparing incoming values
to existing values
update individual panels (via classes or more specific id's)
turn incoming values object into current values object in
preperation for next sql query

If i understand correctly, this could be done like this :
- all your listitems must have a class attribute let's say "list_items".
- after getting data with Jquery you can do a jquery.each() on the list_items, this way you can check if the value of that list item == the new value if not you update your list item.
I hope this answers a little bit your question.

Related

PHP database display in same fields with different anchor tags

I've searched high and low to see if this is possible and came up empty handed. Firstly, here's my code:
<div id="information" style="display:none">
</div>
<?php $seat = mysql_query("SELECT * FROM people WHERE seat='C3-24'"); $row = mysql_fetch_array($seat); ?>
<ul>
<li> <?= $row['first_name']; ?></li>
<li> <?= $row['last_name']?> </li>
<li> <?= $row['seat']?></li>
</ul>
</div><!-- information -->
<div id="c3-24" class="seat">
<a class="trigger" onClick="document.getElementById('information').style.display='block';"></a></div>
</div>
Basically I want to update the li list when I select a div id "c3-25". Now I know that having the WHERE seat="C3-25" will only output the database row of with that but I want to reuse this structure with other locations. From what I read this isn't possible. Ideally I want to have a list of divs (c3-24 to c3-50) and display the corresponding information when the anchor tag is clicked in the li fields.
I've tried putting multiple "information" divs but the information just end up stacking on top of one another.
Any help would be appreciated.
The problem is timing. There are two very separate execution contexts worth considering to understand your problem:
page construction (PHP) - the web server creates HTML to send to the browser;
user interaction (JavaScript) - the user's browser has rendered the page and the user is interacting with it.
Since page construction time happens way before the browser gets the information, it can't possibly implement user decisions (which happen later).
The typical solution to this kind of solution is to break up the application into multiple requests. As a best practice, it's also better to split out your JavaScript into a separate file and use a technique called delegation to reduce the amount of code.
Here's how I'd do it. First, send down the page structure (PHP/HTML):
<div id="information">
<!-- leave empty -->
</div>
<div class="seats">
<div class="seat">
<a class="trigger">c3-24</a></div>
</div>
<div class="seat">
<a class="trigger">c3-25</a></div>
</div>
...
</div>
Then set up the user interaction in a separate JavaScript file:
// setup a click handler on the parent 'seats' div
document.querySelector('.seats').addEventListener('click', function(e){
// check if the target of the click was actually an anchor tag with class=target
if (e.target.classList.contains('target')) {
var
// use the text of the anchor tag to get the seat
seat = e.target.textContent,
// create an XMLHttpRequest to asynchronously get the seat details
req = new XMLHttpRequest();
// handle server result by inserting details
req.onreadystatechange = function() {
if(req.readyState === 4){
document.getElementById('information').innerHTML = req.responseText;
}
};
req.open("GET", "seatdata.php?seat=" + encodeURIComponent(seat), true);
req.send(null);
}
});
Finally, implement a separate PHP script which gets the data for a specific seat (e.g. seatdata.php). Your script should get the seat URL parameter via $_GET['seat'] and use that in your query.
Per Madara's comment, don't use the mysql_query function directly since it has been deprecated, use something better instead.

What is the best approach to handle dynamically generated unique DOMs on a page based on a common single template?

Suppose you have a page in which users can create a new, unique div every time they click a button. The content of the div is mostly based on a common single template on the server side, but as the user can create several of these, the content DOMs ids of the resulting div have to be dynamically generated for each request, so as to be able to select each individual div and its content separately through jQuery afterwards (otherwise, since these divs are based on the same template, they would naturally always have the same DOM Ids, thus making it impossible to select them individually using jQuery)
Let's say you are building a windows system with javascript and jquery. On the server side you have one template that represents the "folder" window; this template has its own buttons, menus, etc, all of them being dom elements with their ID.
The user is then, on the page, supposed to be able to open several "folder" windows, each of which is assigned a different id on its creation, but the contents are the same, since the template loaded is the same for all of these windows. That is to say, provided the user opens 3 "folder" windows, the actual markup loaded in the page may look like the following:
<div id="firstWindow">
<div id="windowContainer">
<div id="windowHead">
stuff
</div>
<div id="windowBody">
<div id="windowInfoButton">stuff</div>
stuff
</div>
</div>
</div>
<div id="secondWindow">
<div id="windowContainer">
<div id="windowHead">
stuff
</div>
<div id="windowBody">
<div id="windowInfoButton">stuff</div>
stuff
</div>
</div>
</div>
<div id="thirdWindow">
<div id="windowContainer">
<div id="windowHead">
stuff
</div>
<div id="windowBody">
<div id="windowInfoButton">stuff</div>
stuff
</div>
</div>
</div>
As you can see windowContainer, windowHead, etc are duplicated as a result of reading from the same template. By itself this is already bad, but moreover I need to be able to select each windowContainer or windowHead using jQuery in such a way that manipulating them in firstWindow doesn't affect secondWindow, so simply switching all ids to classes wouldn't do it.
There are two approaches I can think to solve this:
1) Since I'm using PHP directly as the templating language, I could easily attach some code that generates a randomid or string and replace every DOM e.g. from this:
<div id="someFixedID" class="someClass">stuff</div>
To this:
<div id="<?=$someRandomStuff?>someFixedID" class="someClass">stuff</div>
The problem is that, well, if the template has some 20 or 30 DOM elements, that would greatly pollute it, and I'm trying to have as little code in the templates as possible to be able to quickly iterate on the design.
2) Using jQuery, it's possible to load the template via ajax, loop through every element in the div and change their ids on the fly before showing it. This would help keeping the templates clean, but I'm concerned this method may add an unnecesary overhead on the client side, since it may have to loop through some 20 or 30 elements.
Which method would make more sense in terms of maintainability and performance? Is there another way to approach this I didn't think of?
If I understand your problem you need to create a DIV dynamically with a unique id. Add DIVs with unique IDs using jQuery and then load content from server side in these DIVs. You need to synchronize your client side IDs generate code with server side template names/content.
For Example:
HTML:
<div id='container'></div>
<input type='button' name='create' value='create' id='create'>​
jQuery:
$('#create').live( 'click', function(){
var num = $('div.mydiv').length;
var html = '<div id="myid' + num + '" class="mydiv">My Content ' + num + '</div>';
$('#container').append(html);
});​
Try Here
May be not a perfect solution but hope it will give you a direction.
You could add a parameter in the URL of the Ajax call to get the template to use your client side generated key.
A very rough (not secure) draft:
On the server (template.php):
<div id='<?= $_GET["container_key"] ?>' class='main-container'>
....
</div>
Your ajax call:
var containerKey = Math.random();
$.ajax("/template.php?container_key=" + containerKey, ....)
Use something better than Math.random() (like timestamps, guids, ...) to prevent collisions.

PHP ajax with jquery slidedown

i have a complicated PHP conundrum. I have a constantly updating table in my database (Lets call it TABLE) with multiple records being added a second, these results will be posted using PHP on a page (page.php) using AJAX.
The maximum amount of posts shown are 1 every three seconds, for which i have a relevancy algorithm. I don't know how to merge the jquery transitions with the constantly updated records from the table (Got by AJAX).The best i came up with isn't much better than a hack, and dosen't accomadate for an infinite number of posts.
Jquery:
$(#5).delay(1000).slideDown(700);
$(#4).delay(4000).slideDown(700);
$(#3).delay(8000).slideDown(700);
$(#2).delay(12000).slideDown(700);
$(#1).delay(16000).slideDown(700);
PHP:
Not required
HTML:
<div id='5' class='post'></div>
<div id='4' class='post'></div>
<div id='3' class='post'></div>
<div id='2' class='post'></div>
<div id='1' class='post'></div>
I don't know what to do with AJAX.
Any help would be greatly appreciated,
thanks
If your question is simply how to slidedown the newest appended div, try this:
HTML:
<div id="updatePanel">
<div id='div5' class='post'></div>
<div id='div4' class='post'></div>
<div id='div3' class='post'></div>
<div id='div2' class='post'></div>
<div id='div1' class='post'></div>
</div>
Note: id attributes starting with numbers are invalid.
jQuery
setInterval(getData, 3000);
function getData() {
// call ajax, get data.
// success: function () {...
var id = parseInt($("#updatePanel div:first").attr("id").replace("div", "")) + 1;
$div = $("<div></div>").attr("id", id)
.addClass("post")
.text(dataFromAJAX)
.css("display", "none") // change this to be a class - this is just to make it clear.
.prependTo("#updatePanel")
.slideDown();
}
Example fiddle
I'm not sure, but is this basically checking for new posts every three seconds, and then displaying them with a slide down?
If so, once you've pulled the new posts with ajax, append/prepend the code to a wrapper container, preset to div to hidden, and then slide it down.
I can help with code if this is what you want but you'll need to post your ajax so I can get a better idea.

Change aspects of page with PHP

I'm trying to make my PHP code update parts of my HTML when executed, and I'm not really sure how to do it without relying heavily on javascript and hidding divs etc.
It works in a way that when the user clicks the "tick" or "cross", it updates a database and hides a div whilst showing another. This DB is queried on page load, and a voting bar is loaded with the current total ticks and crosses. There is then a % width set on those bars depending on how many votes each side has.
I've currently got:
<div id="voting">
<a href="#" onClick="updatelikes();">
<img src="/images/tick.png" width="250px" />
</a>
<a href="#" onClick="updatedislikes();">
<img src="/images/cross.png" width="250px" />
</a>
</div>
<div id="votingoff" style="display:none;">
<img src="/images/tick.png" width="250px" />
<img src="/images/cross.png" width="250px" />
</div>
and
function updatelikes() {
$.get("updatelikes.php");
voting = document.getElementById('voting');
voting.style.display="none";
votingoff = document.getElementById('votingoff');
votingoff.style.display="";
return false;
}
function updatedislikes() {
$.get("updatedislikes.php");
voting = document.getElementById('voting');
voting.style.display="none";
votingoff = document.getElementById('votingoff');
votingoff.style.display="";
return false;
}
This works in that it removes one from display, and shows the other one. However, I feel this code is a bit clunky, and I'd like for the "voting bar" to have its width changed and have the values updated. Since the HTML code is generated at page load by the PHP script, I don't know how to update it when "updatelikes.php" or "updatedislikes.php" is loaded, since I feel I would have to have another div that is hidden, then added to it, then show it, and hide the other. I think this could be a clunky, and maybe even slow on some user computers.
Any input is much appreciated, as I'm just totally lost now!
I see you are already using JQuery to access "updatelikes.php" and "updatedislikes.php". You can easily have a value returned to your javascript functions from your php pages:
$.get('updatedislike.php', function (response) {
//Logic in here
});
So in the Like/Dislike you could get the total votes from the database and return it to your javascript function, and then the "response" argument will have whatever you returned from your php function. After the value is returned you can simply re-call whatever you call at page load (in case you return/do exactly what you do when the page is loaded at first).
Here you can find how to return values from your php files to your jquery/javascript functions.
Good luck!
Hanlet

Add strings with ajax from server using phpMyAdmin, jquery

Right now, i'm trying to add a couple of <li>, using ajax. The problem is that i'd like these <li> to use data from a database I have on the server. I'd like to know how to do that! Also, is it possible to use jQuery?
Let's say I have a <div id="listHolder">, where I have a <ul> and then some <li>. Those <li> are the ones I want to change via ajax.
I use phpMyAdmin, where I have a database called t_menuMaterials, and I want to retrieve strings inside m_nom.
I'd also want to be able to change the menu, on a click of a button, change t_menuMaterials to t_menuTextures.
I have been able to populate my menu, but only at the load of the page like that!
$requeteMenuMaterials = "SELECT * FROM t_menuMaterials ORDER BY m_id LIMIT 10";
$ressourcesListe = mysql_query($requeteMenuMaterials);
$targetMenu = "SELECT r_categorie FROM t_ressources ORDER BY m_id LIMIT 10";
$ressourcesListe2 = mysql_query($targetMenu);
$menu2 ='';
while($tbl_ressources1 = mysql_fetch_assoc($ressourcesListe)){
$menu2 .='<li class="secondaryMenu"><a href="#" onClick="test('.$ressourcesListe2.');" ><div>'.$tbl_ressources1['m_nom'].'</div></a></li>';
}
Now, I'd like to be able to change the div (like if $requeteMenuMaterials became ="SELECT * FROM t_menuTextures(instead of t_menuMaterials). I have no idea on how to change those <li> via ajax using my databases and phpMyAdmin.
Its difficult to give you exact advice as you only list small parts of your service side code.
But some general guildlines:
Take a look on jQuery, it has support for ajax calls and also a lot of client side plumbing to update elements.
On the server you have to have som separation of the different calls to the DB so that the client via the URL or POST data can tell the service side script what to do.
There is no way from Javascript to directly call some inner part of a php page, you have to call the page as a regular http request and use URL arguments or postdata to have the page return different information.
jQuery $.get is probably what you need. Basically, have a page that pulls the relevant data from the database, and echo it out to your page. So your page (get-li-data.php, for example) might output:
<li>An item</li>
<li>Another item</li>
And use $.get to get that data and insert it into a div, like:
$.get('/get-li-data.php', function(data) {
$('#div-where-i-have-a-ul').html(data);
});

Categories