I plan to make this commenting system where comments can be posted and updated without refreshing the page ( you can see this on youtube)
Posting comments is understandable ( post to php page from javascript and run SQL query on server side to import it, than return the comment and fetch in html )
Updating is the part I don't understand. How can I refresh the page automatically on certain intervals and add comments? Isn't that going to be a mess when multiple users try to comment at the same time?
I was wondering if anyone can recommend a good way ( just like word of advice ) to achieve this and save me some time
The most common way is to call setTimeout or setInterval in javascript to poll every 5-25 seconds. Basically, you store the idea of the last comment you received on the javascript side, then you call a function that sends this id to a remote server. If there are newer messages than this id, you send all of them back via XML or JSON (usually json is easier to deal with on the javascript side, especially if you use a framework like jQuery).
You can use "Long Polling". Basically it is a technique in which you open an Ajax connection and the server doesn't close until it has some response to send. The client upon receiving this response requests a new connection and waits again for a response.
You can check a tutorial: Simple Long Polling Example with JavaScript and jQuery.
Another really good way would be using a subscribe/publish service.
I'm using PubNub at the moment for Notifications, Comments ect..
I once used a simple technique (no timer used, no total refresh) with a flaw that it shows only new comments, but not edit and delete by others done to existing displayed comments. Be mindful that refreshing the whole comments panel may be unfeasible if you allow "expand / collapse / view more" comments. My simple technique is to have (i) a hidden input element to store the index/primarykey of the last comment displayed (ii) several uniquely identified divs to hold existing displayed comments and ajax refresh or html dom manipulation only that div when actions are performed on it (iii) a div to hold a view more comments button whereby the button will only be displayed if there are more comments to view.
Therefore, whenever a new comment is posted, "the view more comments panel with a button" will be refreshed saying view [X + (# recent new comments by others) + (# your new comment)] comments. Upon clicking the button, it will display 3 more new comments along with "view Y more comments" button.
Related
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).
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.
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.
This is more of curiosity that anything, but I can think of several places (mainly in admin sections) where this could be useful. I know the title is confusing so this is what I mean:
Say you have a form that posts to example_cb.php. example_cb.php is a very large callback page that generates multiple thumbnails of an image, puts them in their respective directories, adds them to a database, etc. You already have the form posting by jquery with a function like this
$.post('example_cb.php', $(this).serialize(), function(data) {
// Success
}, 'json');
Before posting it updates a div to say "processing" of something. Then after it successfully completes the div fades out. However you want the div to show what is happening on the server side. i.e. Converting 200X200 thumb > Converting 350x350 thumb > Adding Records to Database > etc.
How can you accomplish this?
I know it's a loaded question, but I'm confident there are people on here smart enough to figure it out. If you need more info please comment :)
You could do something like -
Write each 'event' update to a database table
Write a page that retrieves the last n events from table
Use something like 'load' to call page update an onscreen div
with the updated progress.
Use 'setTimeout` to keep updating.
This could be accomplished most easily with using the push method, but I'm not too familiar with ajax push or comet technology, so I'll give you a pull solution.
Basically you need to create the initial ajax request to start the processing. Then, you need to have another request running in a tight loop that checks against a php page for the current status. For example, on the php page doing the processing, you can update a _SESSION key that stores the current processing information (like "Converting 200X200 thumb") at each step. Another php page will exist purely to print that information and you can retrieve it with the JS running in a loop.
pusher like services may be used for bi-directional communication.
I'm putting it down for reference, though this would be overkill for such a simple scenerio.
Why use AJAX for dynamic web pages when you can do it only with php?
The main reason to bother with AJAX is User Experience (UX).
Now AJAX won't necessarily improve UX in every single instance so in a lot of places sticking with pure PHP is perfectly okay.
But imagine the case where you have a text field on the site and a link to vote on something. Kinda like this site. When you add AJAX your users won't loose the text they entered in the textfield when they decide to vote on the link! How incredibly useful!
So if you care about your user's experience it is a good idea to use AJAX in situations like that.
PHP creates and outputs the Content to the Client Browser as it's a Server-Side Language and that's what it was built for, so on a request your code will access database, files etc. and then output the constructed html/text to the client.
Ajax just gives the User a more Desktop like feel. For example deleting a record and instead of the entire page reloading just letting the one element disappear from say a list and letting the server know that the record is to be deleted. But Remember to let the User know when you are busy sending data to the server (With a progress bar in .gif format for example). As lot's of user feel that if nothing happens on the screen to notify them, that the application is frozen which means they will either reload the page or just try to click the button again.
But you will need to provide some sort of compatibility with browsers that have Javascript disable and thus cannot use your AJAX functions, just something to keep in mind.
AJAX stands for Asynchronus Javascript and XML, meaning that a page can get new data, without having to reload a page.
PHP cannot send data without reloading the whole page. A user has to press a button, to send data.
An example of AJAX is for example google suggestions or the tag suggestions on this website.