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
Related
I am having a problem where I am successfully setting a URL variable in the form of mywebsite.com/contact/?product=VAR1 from one page to another, and it will be read on the 2nd page with my simple code.
First use is fine but any thing after that is not. There is a problem with the variable not being cleared/re-read/reset. The URL Bar even reads fine in the URL bar mywebsite.com/contact/?product=VAR2 so that first part works.
But the code doesn't want to get the VAR2 part once it has stored VAR1. It just keeps re-displaying VAR1 once it is loaded once.
<?php echo htmlentities($_GET['product']); ?>
If it makes a difference, I am succesfully displaying the ?product= information inside of a jQuery value changer with this:
$(".input-text").val('<?php echo htmlentities($_GET['product']); ?>');
I have tried my own solutions like putting in a unset($product); before the last ?> but no avail.
I have a limited knowledge of PHP/jQuery and would like to use this way of setting/grabbing variable since it is simple. I am using it in jQuery because it can re-write the exact form input-box value with this variable passed along, and successfully send it in my CMS's contact form.
------------------------ updated: added code ------------------------
(I am just displaying all the code logically as I can think of)
#1: Set up the variable into the URL. The first echo getURL displays the url, I add my ?product= and then it gets the item name. This is all fine.
<a href="<?php echo Mage::getURL('webforms/index/index/id/2') ?>?product=<?php echo $_product->getName(); ?>">
#2: My form is set up within my CMS. It has a special class so I can select it exactly within my jQuery. I do not have access to all of this, it is generated by the CMS. The purpose obviously is to get selected products to be rememmberd via this Variable, and serve purpose in the contact form.
<div class="field webforms-fields-enquiryfield">
<label for="field_20">
Product in Enquiry
</label>
<div class="input-box">
<input type="text" name="field[20]" id="field[20]" class="input-text" style="" value="">
</div>
</div>
#3: Now that my area to display, & variable are set up, we use jQuery to insert the variable into the actual value of the input-text form. I am doing this because within my CMS I am not able to simply add it in. I have to use jQuery to replace the text (which is empty box anyway).
$(".webforms-fields-enquiryfield .input-text").val('<?php echo htmlentities($_GET['product']); ?>');
Hope that made more sense.
I have figured the answer to this, the problem was that the CMS Magento likes to cache certain blocks - which is why I could view it first, then my CMS would store the variable but not erase it. No matter what kind of fixes I tried to disable caching, no go.
Instead I ended up using the following code, using a # variable, and some simple JavaScript that anyone can understand. I will be using this in future projects no doubt! Very easy variable passing ...
if(window.location.hash) {
var hash_value = window.location.hash.replace('#', '');
$("my-css-input-field-or-whatever-you-want").val(hash_value);
}
The hash_value can be used in a variety of ways now I suppose, and this works well around my Magento set up, it does not get cached/stored. Grabbing the URL location & hash instead.
(And the PHP used, simplified for anyone to replace/reuse within a CMS)
<a href="[GetBaseURLfromCMS]#[MyDynamicVariableHere] ">
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.
I see this on most website.whereby once the page is loaded, they have a kinda image advert whereby it changes, maybe it has a set timer or something. And if you hover the cursor around the images, there's always a different link attached to it, that leads you to the page where it has been instructed to.How can i achieve similar thing. Am thinking Php or maybe javascript, but would prefer php.
You can use some javascript.
Let's say, you have this markup:
<a id='ad_link' href="http://url1.com">
<img src='img1_url' />
</a>
And you receive this data from somewhere (for example, from your server via AJAX).
{"link": "url2.com", "img": "img2_url"}
Then you update your ad with this (using jQuery):
function updateAd(ad_data) {
$('#ad_link').attr('href', ad_data['link']);
$('#ad_link img').attr('src', ad_data('img'));
}
Now, you can request new information in a various ways. setTimeout() or setInterval() are easy and probably the most obvious ways.
php is server side language not client side, so if you already have images in browser php can't do anything with it, you can just use javascript (client side) to call to server for images, or another alternative to AJAX is that you will render all images you want to switch between but displayed will be just one and with javascript you will hide that image after some time and reveal another.
html:
<img id="first" src="first.jpg"/>
<img id="second" src="second.jpg" style="display:none"/>;
javascript:
setTimeout('change',3000);
function change() {
$('first').hide();
$('second').show();
}
something like this but better
Hi I just want to know what the best practice is for dynamically creating html. I can do it in two ways
Direct PHP
<div id='id-here'>
<?php
$user->id = $_GET['id'];
$user->displayUserInformation( );
?>
</div>
jQuery ajax(js script called on page load)
$.ajax({
type: 'GET',
url: 'inc/user_information.php',
data: 'user_id=user_id', //assuming user_id value was already set.
success: function(html)
{
$('#user_information').empty().html(html);
}
});
Note: This code doesn't exist and is purely for showing what I mean^^ I also know jQuery load, but prefer to use jQuery ajax for complex stuff.
Thanks!
The PHP method is certainly more reliable, as it doesn't require javascript in the client. For information that isn't expected during a page's lifetime, or indeed a user's session it also makes a lot more sense. I don't imagine the information on a user is likely to change that much during a page view.
However, if there is some data that's expected to change, say a post count or something, then use PHP to set the initial value, then use ajax to update it only when the value actually changes.
I wouldn't worry about which is faster... the difference would probably be negligible. But bear in mind that some users do have JavaScript turned off... if you want to support those users, it's worthwhile taking the extra effort to do it in PHP.
My rule is that if it can be done on the server, do it there. Then you can be absolutely sure of the results for all users.
u get it all wrong, first one is not a 'dynamically created html", user sent a request, PHP process it, and return the HTML, and your browser render it
2nd one is your browser already load HTML, and u try to use jquery to simulate another request of the same process of the 1st one
In your examples, if you show user info like this, method 1 will not require another data fetching from the server as in example 2 (2 HTTP requests total, 1 for original webpage, 1 for the ajax), so it is faster.
usually, generating static data inside a page like this (in example 1) is different from AJAX, where content is provided to the user, and only update with the new data using AJAX without updating the whole page's content.
Maybe what you mean is: should the data be provided together with the original webpage, or should it be left empty, and then use AJAX to fetch the data to display it. It would be better usually to provided data at first, instead of letting the user wait for another trip to the server to see the data.
I believe that loading from PHP as static loading would be better and more reliable. However loading from AJAX will push the results one time, not as static loading, data will be loaded in portions...
Along the same lines, which is faster within a php file. This is more for SEO and "best practice" than for actual user experience. I'm using wordpress, and I'm working within php files. Most of it is php, but I have four lines of html within the file. All are exactly the same. I could loop through the four lines with php, or copy and paste the four lines of html. I don't expect to ever change the code, so php doesn't seem to present any other benefits.
Here's my code:
HTML version (well mostly)
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" class="bracket" />
OR the php:
for($i=0;$i++;$i<4){ ?> //start loop, 4x
<img src="<?php echo get_bloginfo('template_directory').'/images/bracket.png';?>" />
//Image path using php
<?php } ?> // end loop
THANKS ALL!
Lets say a member is displaying 10 images by default but a link will display the rest of the users images by having them slide down when a user clicks a link.
So my question basically is I want to be able to display all the users images buy having them slide down when a user clicks on a link <a>. How would I be able to tackle this problem using JQuery, PHP & MySQL?
check this plugin, it's not what you asked, but it's (IMO) a better solution
http://www.appelsiini.net/projects/lazyload/enabled_fadein.html
BTW : PHP and MySQL are arbitrary in that question since it depends how your images are stored on the server
This will take care of it.
<script>
$(document).ready(function() {
$(".more").toggle(
function() {
$(this).text('less');
$(this).parent().children(".bottom_images").slideDown("fast");
return false;
},
function() {
$(this).text('more');
$(this).parent().children(".bottom_images").slideUp("fast");
return false;
});
});
</script>
<style>
.bottom_images {
display: none;
}
</style>
<div class="container">
<div class="top_images">
<?php
//num images to originally display
$num_show=10;
//current position
$i=1;
//some code to get user images
//from database etc
foreach($images as $image_url) {
if($i==10) {
echo '</div><div class="bottom_images">';
}
echo '<img src="'.$image_url.'" />';
$i++;
}
?>
</div>
more
</div>
Obviously there is some pseudo code for retrieving the user images as there are a number of ways you could get the images eg. from database (as a blob or text url), scanning the file system, user input etc etc. Also I have made it so you can add multiple containers (multiple users) into the one page.
It depends on various aspects how do you want to do it.
You can use LazyLoading as provided by Yanick Rochon
You can preload all the images and simply show the hidden ones when
clicked.
You can also load additional images using AJAX
You can load the visible images first and after all they're loaded - preload invisible images so to show them instantly after clicking a link
Describe your problem a little bit deeper.