As was foretold, we've added advertisements to the forums! If you have questions, or if you encounter any bugs, please visit this thread: https://forums.penny-arcade.com/discussion/240191/forum-advertisement-faq-and-reports-thread/
Options

AJAX question: How to reload section of page without refreshing entire thing?

frankthetankfrankthetank Registered User regular
edited August 2008 in Help / Advice Forum
Hey there!
I've got a fairly simple working PHP script here that basically outputs a random row's information from my database table to my website on each page load. Thing is, the user has to manually 'reload' the browser (causing the whole page to reload each time) for the script to pull an new entry. I am looking for a solution that will reload my script every 5 seconds or so without reloading the page. I understand this might be a job for some AJAX functionality, but I am quite new to javascript. Any pointers?
<?php
	
	// this file just connects me to my database 
	require('inc/db_connect.php');
	
	// creates the variable $random which stores a random ID from the `sponsors` table
	$query_sponsors_ids = mysql_query("SELECT `id` FROM `sponsors` ORDER BY RAND() LIMIT 1");
	
		while ($output_sponsors_ids = mysql_fetch_array($query_sponsors_ids)){
			$random = $output_sponsors_ids["id"];
		}
	
	// passes the $random variable and outputs its corresponding URL & Name to the frontend.
	$query_sponsors = mysql_query("SELECT * FROM `sponsors` WHERE `id` = $random limit 1");

while ($output_booya = mysql_fetch_array($query_sponsors)){
echo '
	<a href="'.$output_booya["url"].'" target="_blank">'.$output_booya["name"].'</a>	
';
}
		
?>

Providing gibberish to the masses. Fluently. Since 2004
www.fluentgibberish.com (a web comic)
frankthetank on

Posts

  • Options
    Jimmy KingJimmy King Registered User regular
    edited July 2008
    First off, have a look at jQuery, it makes this sort of stuff so much easier most of the time.

    As a very high level overview, you'll want to look into the javascript function XmlHTTPRequest and whatever the IE equivalent is that I can't remember - that's how your page/js will post the data to your back end and get the data back without reloading.

    After you've gotten the data back you'll update the data by manipulating the DOM tree, again with the javascript.

    jQuery makes both of these things one hundred billion times less hassle. I recommend doing some basic DOM manipulation in the very least without jQuery, though, so that you have a general idea of exactly what it is the jQuery libs are doing for you.

    Jimmy King on
  • Options
    frankthetankfrankthetank Registered User regular
    edited August 2008
    Thanks for the pointers!

    I defiantly got a better understanding of the DOM through w3schools, and how to go about manipulating it by using jQuery.

    However, being new to the jQuery world, I am still looking for the ideal event handler for my project. I've got a test page set up here which shows where I am at. My goal is to have my sponsors list cycle every few seconds on their own. I've got it set up right now so that clicking on the blue title 'sponsors' (top middle) will reload the script (utilizing jQuerys 'load' event). Not exactly what I'm after, but I can't seem to find an event which will 'load script every few seconds on its own' instead of 'load script on click'. Perhaps a jQuery Ninja out there can point me in the right direction?

    frankthetank on
    Providing gibberish to the masses. Fluently. Since 2004
    www.fluentgibberish.com (a web comic)
  • Options
    DaenrisDaenris Registered User regular
    edited August 2008
    Not sure if it's the best way to handle that or not, but check out the Javascript functions setTimeout/clearTimeout and setInterval. If you want it to just keep changing the whole time, setInterval would be the way to go. Basically if you have a function setSponsor that reloads the sponsor info, you'd call something like setInterval("setSponsor()",5000) which will call setSponsor every 5 seconds.

    On another note, your code doesn't really seem to work the way you want it to right now. When I go to the page and click on sponsor, it loads one up, but clicking again never changes the sponsor. The only way I was able to get it to display a different sponsor was by manually loading the sponsor.php page until it displayed a different sponsor, then going back to the main page and clicking the Sponsor title. Without seeing your php code I have no idea why it's acting this way, unless it's storing the result of loading sponsor.php somewhere, so it's only updating when reloading sponsor.php.

    Daenris on
  • Options
    Jimmy KingJimmy King Registered User regular
    edited August 2008
    To get it to run continuously my first thought is to just have the method that does the switching call itself recursively with some sort of timer/pause in there. You would just bind this function to document.ready(). I'm not sure how ugly this might be in terms of resource usage if the person sits on the same page for 3 hours or something.

    Something like so:
    $(document).ready(function(){
    
    // or use setInterval here as Daenris suggested
    while(1) {
      rotaterThingy();
    }
    
    });
    
    function rotaterThingy() {
    // code to do the rotation crap
    
    }
    

    edit: edited for less shitty code example/suggestion.

    Jimmy King on
  • Options
    DaenrisDaenris Registered User regular
    edited August 2008
    Jimmy King wrote: »
    To get it to run continuously my first thought is to just have the method that does the switching call itself recursively with some sort of timer/pause in there. You would just bind this function to document.ready(). I'm not sure how ugly this might be in terms of resource usage if the person sits on the same page for 3 hours or something.

    That's pretty much what setInterval does, with a built in timer so that it only calls the function every X milliseconds.

    Daenris on
  • Options
    Jimmy KingJimmy King Registered User regular
    edited August 2008
    Daenris wrote: »
    Jimmy King wrote: »
    To get it to run continuously my first thought is to just have the method that does the switching call itself recursively with some sort of timer/pause in there. You would just bind this function to document.ready(). I'm not sure how ugly this might be in terms of resource usage if the person sits on the same page for 3 hours or something.

    That's pretty much what setInterval does, with a built in timer so that it only calls the function every X milliseconds.
    Ah, brilliant. Now that I read your post again, that's pretty clear. Not sure why it didn't click the first time.

    So yeah, in your $(document).ready() stuff ust do a setInterval that calls your rotating function and you're set. It probably also does it the smart way and just does it in a while() loop rather than recursively calling the function, which is way smarter, since that won't cause an ever growing memory footprint like the recursive crap would.

    Jimmy King on
  • Options
    frankthetankfrankthetank Registered User regular
    edited August 2008
    The Javascript function setInterval does sound like what I could use for sure- however the function I am hoping to execute every X milliseconds is a PHP script which gets its values by querying a SQL database. It seems to call up the first entry as it should (randomly calling an entry from the DB) but it doesn't seem to reexecute every X milliseconds. I'm thinking this is because its a server side script...?

    A solution I thought might work would be to alter my PHP script to call all the items in the DB, put them into an array, and have javascript pick a random array ID to display using this function thus keeping it client side. Would a solution like that be overkill?

    frankthetank on
    Providing gibberish to the masses. Fluently. Since 2004
    www.fluentgibberish.com (a web comic)
  • Options
    Jimmy KingJimmy King Registered User regular
    edited August 2008
    Yeah, I think you're not quite doing it right. Here's what you'll need to do, more or less.

    1) setInterval calls function bobo()
    2) bobo() does an XmlHTTPRequest to your PHP script which returns the results as either an xml or json object (use json, it's better) - use jQuery for this so that it can figure out the correct way to make the call as IE uses a different one and who the hell wants to bother with browser functionality detection?
    3) bobo() then updates your web page - either directly or by calling another javascript function

    Jimmy King on
  • Options
    frankthetankfrankthetank Registered User regular
    edited August 2008
    Big thanks to you guys for the help! I ended up using the setInterval() function in Javascript.
    I shelved the AJAX idea until my research and confidence on the subject increase, and in this case it wasn't 100% necessary to go the live refresh route anyway (though I plan on getting it figured because the application elsewhere will be useful). Heres what I ended up with that works famously.

    Finalized Breakdown:
    -PHP query to call every sponsor from the DB, and javascript to enter each into a javascript array
    -Set a javascript variable to randomly choose 1 entry out of the number of entrys in the array
    -setInterval() on the variable calling 1 entry from the list so it 'refreshes' every few seconds without refreshing the page. Woot!

    Only downside is that if a user loads page and then admin uploads a new sponsor to the array, the page will need to refresh in order to rebuild the array with the new entry (as opposed to an AJAX solution which would have rebuild the array live). No biggie though :)

    Thanks again for everyones' help!

    frankthetank on
    Providing gibberish to the masses. Fluently. Since 2004
    www.fluentgibberish.com (a web comic)
  • Options
    Nova_CNova_C I have the need The need for speedRegistered User regular
    edited August 2008
    I didn't respond to this before since I've never worked with PHP, but a non PHP solution is to have an invisible frame:
    <DIV STYLE = 'display:none;'><IFRAME></IFRAME></DIV>
    

    And then run ONLOAD scripts on the page that is loaded in the IFRAME. That's how I do it for my company's web applications and it's pretty slick. It makes the actual loading invisible to the user and allows me to change anything I want on the display page without have to refresh.

    Nova_C on
  • Options
    frankthetankfrankthetank Registered User regular
    edited August 2008
    Quite right! iFrames could have totally worked too. I suppose I could have had a page with my PHP script calling a single entry randomly from the DB that would refresh itself every few seconds, and then referenced that page with an iFrame and had it do the magic. :)
    I guess I'm a sucker for doing things the hard way sometimes ;)

    frankthetank on
    Providing gibberish to the masses. Fluently. Since 2004
    www.fluentgibberish.com (a web comic)
  • Options
    Nova_CNova_C I have the need The need for speedRegistered User regular
    edited August 2008
    It's especially valuable for server side scripting (Is PHP Server side? I'm not sure). I run everything through Java servlets, so I have a powerful back end to my web apps. The ONLOAD script is dynamically written by the Java servlet according to what data was requested and the ONLOAD script just updates the parent frame as necessary. So really, all my database requests and data processing is handled in Java, which I love.

    The best thing, which is only tangentially related, but whatever, is my dynamic html scripting. I have Java code that writes dynamic javascript code that writes dynamic HTML to a DIV's innerHTML property. Crazy.

    EDIT: The biggest benefit is I can use that database layer to write data to the database without having to navigate the main page anywhere. So it removes a metric fuckton of the limitations of HTML.

    Nova_C on
  • Options
    frankthetankfrankthetank Registered User regular
    edited August 2008
    That does kick the proverbial ass. Sounds like we're using our respective languages to do the leg work of dynamic content loading. PHP is indeed server-side and through the magic of AJAX it can function as you've described the java code you have made. I'm still picking at the tip of the AJAX iceburg, and have yet to give java a shot.

    frankthetank on
    Providing gibberish to the masses. Fluently. Since 2004
    www.fluentgibberish.com (a web comic)
Sign In or Register to comment.