Refresh a DIV with AJAX that requires MySQL queries + PHP - php

I am currently working on a website that is coded primarily with PHP/MySQL and HTML5 as a means to learn the code and become better. I used to work for a forum that used AJAX to reload the latest posts as if the user had just refreshed the webpage, except it just changed the content dynamically without a full reload.
My webpage: http://vgrnews.com
My specific situation is as follows: The homepage loads the four latest announcements and (soon to be) comments from the MySQL DB and displays them soonest -> latest. It is inside of a div called maincontent.
What I want to do: Have the announcements show up dynamically with AJAX regardless of the user refreshing or not. It would probably poll the server roughly every 5-10 seconds.
I don't plan to keep the homepage refreshing like that, but once I add more content it would be good to know how to refresh a div at regular intervals. I have read up on AJAX, but I don't quite understand all of the logistics, they just give you the code and expect you to pick it up. It is hard to morph the code to be applicable for my website if I don't understand it.
Sorry for the long read and thanks for all the replies!

function reload_content() {
$('#latest_post').load('ajax/get_latest.php');
}
window.setInterval(reload_content, 10000);

I will clarify on Alexander's answer for you. What the load() function is doing is performing an AJAX request to the given URL, and then setting the HTML of the selected div(s) to be the returned content. This means that your server should return proper HTML (and only the HTML you want in that div).
You can see http://api.jquery.com/load/ for more information on load().
If you plan on having your server return an JSON (or XML) representation of the information, you will have to use a jQuery get() (http://api.jquery.com/get/), and then process the returned data with a callback.
Note that both get() and load() are simply implicit applications of the jQuery ajax() method (http://api.jquery.com/jQuery.ajax/)
EDIT:
The setTimeout is just making the browser call the function ever x milliseconds. This is what will have it check every x seconds.

Related

OnHover run php script

Okay I'm not really sure how to approach this. I have a user-generated post board where people post, it drops down onto a list of a bunch of posts. When you click on the ID number of the post it will bring you to a separate page with just that post and the comments on the post. I want it so when you hover over the href it drops down something that tells the user there are x amount of comments on this post. This way people know if there is comments without switching pages and also being able to be able to click the href still and go to the postid page.
I assume some ajax/jquery/javascript would be used to accomplish this but since I'm fairly new to ajax and jquery I'm not certain how this would be done. Thank you!
For a hover effect, it would be better if that information was already stored on the page and just hidden. Then when the user does hover, you can just un-hide it and have it positioned where you want, and then hide it again when their mouse leaves the area. Using AJAX requests for this purpose would waste away a lot of HTTP requests for such a tiny amount of information.
Really, you could do the hover effect using pure CSS if you wanted too (I would).
Since a hover happens fairly often, I wouldn't use it as the default event to fire an AJAX-request. This would increase the HTTP-traffic enormous. See if you can fetch this information when the page is build (and put it in then) or use something else like a "preview"-button for the event.
Anyways, this would be the basic workflow if you want/need to use AJAX:
Write a PHP-script (or any other language you use) which fetches the number of comments (and what else you want to display) from the database (or where your data is stored).
This script should then be called via AJAX (with $.ajax() from jQuery for example). As the expected return-type you would then use json.
The script which fetches your data would then create an object, use PHP's json_encode()-function to encode this object to JSON and echo it out.
This JSON-object will then be available in the success-method of the ajax()-method from jQuery. Then, you can access its members (e.g. the comment-count).

Update a Div Automatically with Jquery When New Record Added in MySql Database

I'm making a Social networking website for my friends. i wanted to know how i would Update a Div containing few inserted records of the database, when a new record is added in the database. In short you must have seen the live notifications of facebook, which fade in when someone does something . this all happens without the refreshing of the whole live notification div. only the new notification is prepend to the div.
I would like to do this using jquery and AJAX as i have good knowledge about them. and PHP as the server side language.
Thank you in Advance.
P.S : I have searched many websites for the solution, but couldnt find it anywhere. i Even tried going through facebook's Source code but couldnt find it there too ! I hope someone helps me here ! *crossed fingers*
You can either use Ajax Push to send a notification that the post is updated, or you can make it pull-driven. The latter would probably be easier for you if you already know jquery and Ajax with PHP.
Periodically check for new records on an interval (using setInterval, for example) and if you find them, load them to the DOM and fade them in. The interval doesn't have to be very small and waste resources .. maybe something as long as every 30 seconds will do.
setInterval('checkForUpdates', 30000);
var lastTime = (new Date()).getTime();
function checkForUpdates() {
$.get('/php-page-that-checks-for-updates.php?timestamp=' . lastTime
, function (results) {
if (results) { /* fade into dom */ }
}
);
lastTime = (new Date()).getTime();
}
PHP page:
$timestamp = $_REQUEST['timestamp'];
$results = query('SELECT post FROM posts WHERE postTime > "$timestamp"');
echo fetch($results);
As others suggested, you can also mark posts as "read" and use that as an indicator instead of the timestamp, which will also solve a time zone problem with my example. I wouldn't want to add an extra column just to do this, but if you already have one for some other reason it'd be a good idea.
EDIT: This is a pretty old answer, but if you can still do it I would use WebSockets instead of any kind of ajax long polling. I don't think that PHP is a great language (I would suggest using socket.io with Node.js), but it is possible.
Basically it goes something like this:
Create a javascript function on your page that makes an ajax call (with jquery or native xhr or what not) to a php page. The php page keeps track of "new stuff" and returns it when called. The js function, when receiving data, add new tags (divs or whatever) to the notification bar. The function is called every once in a while with javascript's setTimeout function.
If some of these steps are confusing to you please ask a more specific question.
You can use jQuery's $.getJSON() method to access a PHP page. This PHP page would grab all unread notifications (you could add a column in your notifications table called "read" and set it to 0 for unread and 1 for unread) and return them as a JSON feed.
Parse the JSON and make each one a div that shows up on the page. Then wrap this all in a setInterval() and run it every millisecond (or half a second, or quarter of a second, it's up to you).
Also, to mark them as read, set up a click event on these divs that you created from the JSON notification feed. On click, it will contact another PHP page (you can use $.post or $.get) which will receive the id of the notification, for example, and change the read column to 1.

PHP - Allow users to vote without loading another page/reloading the current page

I want to put Thumbs up/Thumbs down buttons on my website.
There will be quite a few of them displayed at once, so I don't want to have to do a POST and reload the page every time the user clicks on one.
I thought of using re-skinned radio buttons to choose Thumbs up/Thumbs down, but that would require the user to click a submit button.
So how do I do this? I am open to using JavaScript or some other form of Client-Side scripting, so long as it is built in to most/all web browsers.
Thanks!
YM
I would take a look at using jQuery, http://jquery.com/ It is a WIDELY used library and there is tons of support for it both here and # jQuery's website.
You could easily assign all those thumbs to do an ajax post to a save page with the correct id and the user would not know the difference
You're definitely going to need to use JavaScript on this. Well, there are other client-side languages that could technically do the job (ActionScript, for example), but JavaScript is definitely the best way to go.
Look into AJAX (Asynchronous JavaScript And XML). This is just a buzzwordy way of saying use the XMLHttpRequest() object to make page requests with JavaScript without reloading the page. Here's a good tutorial: http://www.w3schools.com/ajax/default.asp . Note that, despite the word "XML" being in the title, you don't have to use XML at all, and in many cases you won't.
What you'll basically do is this:
Have your thumbs-up and thumbs-down buttons linked to a JavaScript function (passing in whether it's a like or dislike via a function argument).
In that function, send a request to another page you create (a PHP script) which records the like/dislike. Optionally, you can have the PHP script echo out the new vote totals.
(optional) If you decided to have your PHP script output the new results, you can read that into JavaScript. You'll get the exact text of the PHP script's page output, so plan ahead according to that -- you can have the PHP script output the new vote totals in a user-friendly way and then just have your JavaScript replace a particular div with that output, for example.

When to use AJAX

Let's say we have a page written in PHP. This page loads by it self a template with header, body and footer and print this out. Now let's say that in the body of this page we would like to start a loop and load some posts (messages taken from a database).
We also need the page to load new posts every 10 seconds, if any, without refreshing the page (classic AJAX). This ajax call will use JSON and AJAX and micro templates.
Now i'm just wondering:
Do we really need PHP to load posts the first time the page is loaded? Can't we just start that Ajax call and load posts with Ajax instead? (Notice that the existing ajax call would be kept as it is, since it loads posts starting from the latest loaded (in case of no posts, that would mean all posts).
If you did not understand my question don't hesitate to let me know.
In this situation I think the simpler approach is the let AJAX handle it, if you do let php load the initial messages, you'll have two places in code, that you'll need to maintain to perform identical jobs.
I think you are asking how you should load the posts the first time the page is accessed. If so: When the page firsts loads, have some PHP that prints out the existing posts. Then, add some JavaScript to update the page with new posts every 10 seconds. This is a matter of preference. You might want there to be no posts when the page first loads, and then use Ajax to get the existing posts once your page has loaded.
Edit:
I agree with jondavidjohn that you might be better off using pure Ajax. However, you could always isolate the code that fetches the pages into a separate function. That way, the script that generates the page calls the same function as the script that is called via Ajax.
The drawback with that technique is that it doesn't downgrade gracefully. So people with javascript disabled will not see any posts.
I'd recommend outputting some data with php - AJAX requires JavaScript which many people don't have activated.
Why not, instead of having the browser poll the server for new posts, have the browser push new content to the browser when it is available using the likes of node.js?
I designed my site with AJAX exclusively, and it works perfectly except for one rather major issue: Using AJAX requires JS to be enabled. Of course, if users trust your site, this is not a problem, but if they don't, then an AJAX solution won't work unless you put the entire page in a noscript tag.

Ajax problem not displaying data using multiple javascript calls

I'm writing an app that uses ajax to retrieve data from a mysql db using php. Because of the nature of the app, the user clicks an href link that has an "onclick" event used to call the javascript/ajax. I'm retrieving the data from mysql, then calling a separate php function which creates a small html table with the necessary data in it. The new table gets passed back to the responseText and is displayed inside a div tag. The tables only have around 10-20 rows of data in them. This functionality is working fine and displays the data in html form exactly as it needs to be on the page.
The problem is this. the HREF "onclick" event needs to run multiple scripts one right after the other. The first script updates the "existing" data and inside the "update_existing" function is a call to refresh a section of the page with the updated HTML from the responseText. Then when that is done a "display_html" function is called which also updates a different section of the page with it's newly created HTML table. The event looks like this:
Update
This string gets built dynamically using php with parameters supplied, but for this example I simply took the parameters out so it didn't get confusing.
The "update_existion() function actually calls the display_html() function which updates a section of the page as needed. I need to update a different section of the page on the same click of the mouse right after the update, which is why I'm calling the display_html() again, right after it. The problem is only the last call is being updated on my screen. In other words, the 2nd function call "display_html()" executes and displays the refreshed data just fine, but the previous call to update_existing() runs and updates the database properly, but doesn't display on the screen unless I press the browsers "refresh" button, which of course displays the new data exactly how I want it to, but I don't want the users to have to press the "refresh" button. I tried adding multiple "display_html() calls one right after the other, separating all of them with the semicolon and learned that only the very last function call actually refreshed the div element on the html page with the table information, although all the previous display_html() calls worked, they couldn't be seen on the page without a refresh of the browser.
Is this a problem with javascript, or the ajax call, or is this a limitation in the DOM that only allows one element to be updated at a time. The ajax call is asynchroneous, but I've tried both, only async works period. This is the same in both Firefox and Internet Explorer
Any ideas what's going on and how to get around it so I can run these multiple scripts?
I'd recomment you to use jQuery javascript library. It has some funcions, like live() that can "wait" for that table to appear on the browser and apply the remaining functions on it.
Also, it's a great set of functions that will certainly help you out reducing the ammount of code you write, making it more human-readable.

Categories