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).
Related
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.
I want to make a webpage where an user can add the title from a book he has read. These changes are reflected in real time on a list that contains all books he has introduced on the database, without the need to press any "reload" button. By example: there is no need to refresh (F5) the page to see the last book added.
I don't know if I can do this in PHP or in any other language, so I would like to know which is the best suited for something like this.
Thank you.
I think you are looking for Ajax. Would be able to asynchronously update the section of the page (the post in this case) without the need for page refresh.
You will want to do this with javascript, using the onchange event, and for a discussion on this you can look at: Call Javascript onchange event by programatically changing textbox value.
Basically, you react to the data being changed, then just send it immediately over using ajax to the server, but, you need to be aware of two things.
First, how will you handle errors, such as there is no book with that title, or the length is too long. I tend to put the error message in or by the place where they had the bad data.
The other is that you need to pass back the id when the data was inserted, so that when they change it again you can just do an update, so you will need to store that. I tend to put the database id I need in the element id, but you can keep it in an array in javascript, since it will maintain state for you.
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.
Context
I'm working on a project that I'd like to make more dynamic with PHP + AJAX.
I'm using jQuery for the AJAX part because I totally suck in Javascript, and anyway it seems to be worth something.
I reached a point where my application needs to use a form to send a post, and I want to use an ajax call to perform this action. In the page I'd like to send the post, there is also a list of the most recent 15 posts submitted.
First question: Should I just forget about it and use just PHP?
The action
The user writes something in the <textarea></textarea> and clicks on a <a id="myPostSubmit">Submit</a> that is the handler that I'll manage on the jQuery script with something like $("#myPostSubmit").live('click', function() { /* here i make the ajax call */ });. If the post is successfully submitted we are going to do something (I'll talk about it in the next section), either we will alert the user using my showAlert(text) function, that shows a black box for 4 seconds with the text in it.
Second question: Should I manage the click event in any other ways? Should I create a function, such as sendpost(post) and attach it into the HTML onclick="" event?
If the post is successfully sent
I'd open a discussion about 2 options:
We refresh the page [not actually
loading the entire page but making
another ajax call that retrieves the
posts lists and makes disappear the
old one, load the PHP file to
retrieve the new posts (including
the one we just sent), and then make
the post list appear]. Pro: 1) We are sure that what the user is reading after the post list is loaded is the real post sent. So it actually double checks the action. 2) We load also some possible posts sent in the mean while. Cons: 1) We have to create a PHP file that gets the post list template, slicing the template of that page in 2 files. 2) It doesn't really seems that smooth to me.
We just use Javascript to get the post template, add it to the list. Pro: 1) We make it really smooth, without reloading the entire page. 2) We don't need of any PHP file to reload the page. We just use Javascript (jQuery). Cons: 1) How do we get the post html template to add it to the list? 2) How do we get the user (logged) informations without PHP?
Third question: Is it better the 1st or the 2nd solution? Would you provide a even better 3rd solution?
The PHP page
The PHP page that will receive this AJAX call is : ?p=action&a=sendpost. The page require $_POST['myMessage'] to be set and not empty and nothing else. The page itself will get all the user infos from the cookies and will manage to perform the needed query.
The application
It is divided in 3 parts: App, Template, Library. Basically each page of the application has its own .app.php and .tpl.php file.
The .app.php file manages the building
of the basis of the page, using classes
and other stuff from the library. In
our case it retrieves datas from the
database and put them into
variable.
The Template is called at the end of the .app.php file. The .app.php file send to the template the retrieved data and the .tpl.php file outputs them.
The library is used to contain the classes and functions we need in the application file.
Fourth question: Is this a good way of manage my web application?
Edit: What about returning the alert message to the user?
I read about an option, inside $.ajax() that will manage the response on success or in error. The documentation about it is very simple and I didn't get it.
Fifth question: How should I return (from the PHP file) the error
or the success?
First question: Should i just forget about it and use just PHP?
Well, you application will relay on JavaScript if you use ajax, this days i think it just fine ;)
Second question: Should i manage the click event in any other ways? Should i create a function, such as sendpost(post) and attach it into the HTML onclick="" event?
Create a function and bind onclick. Code will be more readable ;)
Third question: Is it better the 1st or the 2nd solution? Would you provide a even better 3rd solution?
My solution: ajax submit the form and on callback insert new comment in to the list or display error message if user can't comment.
Check jQuery serilize() for submitting forms data with ajax.
Fourth question: Is this a good way of manage my web application?
It's just fine ;) When you application get's bigger you will have to redesign it, but don't do it know, do it when current solution becomes to hard to work with.
Read some good book on building MVC framework. And on programming patterns in general.
You seem to be on the right track with everything. There are lot of opinions called "best practices" about how to exactly attach event handlers, how to reload the data on the page and how to organize your application, etc, but I personally would rather build more software instead of worrying about details like that. The details will come to you eventually.
I personally find that updating whole chunks of server-side-rendered HTML on the page is more robust solution, but I have seen people getting excellent results with templates.