I'm trying to add this functionality to my PHP cart
Let's suppose we have two pages: catalog.php and cart.php
What I would like to do is:
User clicks on "Add to cart" button on catalog.php
and triggers an ajax request via jQuery to cart.php sending it info about which product was added (this all works as expected) and makes the cart.php page update itself by including the just added product without a page refresh (this is the part I can't get to work).
If I put the two pages side by side and click "Add to cart" nothing happens, only on page refresh (cart.php) I see that the new product was added.
Is there a way to archieve this?
EDIT: I wasn't clear enough i'm sorry my bad
The pages are presented in a standard way, no frames no popups
The "app" works as expected and this will unlikely be an issue for users
The "side-by-side" thing was just because i would like to know a way to obtain this functionality since i can see myself using it in the future for pretty much anything (DOM manipulation of pageB from pageA, CSS, etc.)
You can simulate this by having an AJAX call on Cart.php which checks the (session/db) to see if something new has been added.
I'd suggest something like...
Cart.php makes an AJAX call every 10-60 seconds and asks for a complete list of products in the cart.
Any new items are added to the table as appropriate (either by checking product Ids or OrderItem Ids). You should also update quantities/etc.
This way, no matter what mechanism is used to add items, the cart will see them before too long.
Obviously, the more often you poll, the quicker the cart will update but the more load you'll put on the system.
Now the reason it's not directly possible is that AJAX requests are always initiated by the client, not the server.
There is one other potential workaround which omits frequent polling and gives near-instant updates but it's a little more complex to implement.
It's known as long polling (see this answer) and effectively what happens is this...
Client sends AJAX ("A") request to the server for cart information.
The server accepts the request but does nothing (as if a long-running script were processing)
When a new shopping cart item is received via AJAX ("B"), the server responds to Request A with details and The cart page updates the table as appropriate.
If no cart activity is detected within a reasonable timeout (30-120s), the server responds with a "No Operation" response and closes the connection.
Whichever response the client receives, it immediately opens a new AJAX request and starts all over again.
Effectively, your PHP script then deals with checking the database/session/etc for updates and the client is only waiting on a "slow" server. This is how twitter implement their various feeds via APIs - each new tweet is returned on a new line as they're generated.
Note that this can be a pain to implement as you're just shifting the polling from the client to the PHP but it does make it more elegant from a JavaScript point of view, removes the delay and reduces wasted network overhead.
Last I checked, only pages opened with window.open (or opened with a <a target="_blank"> link) can talk to each other.
So in catalog.php call cart = window.open('cart.php'), cart contains the window object of the page that opened it, so you could do:
cart.document.getElementById('whatever').innerHTML = '<p> new content</p>';
To get windows to talk to each other side-by-side w/o one opening the other you can use HTML5 local storage, but that takes some more advanced wizardry.
Related
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.
First some background:
I've developed an informal feedback system for disabled learners that collects data and periodically emails out the results as percentages with piecharts.
QTV http://www.mwjt.co.uk/QTV.jpg
Currently it uses 2 PHP webpages:
-The first reads the question from the database.
-The 2nd (a thank-you page) takes the input (as GET) and submits it to the database and then redirects back to the first with an arbitrary random string variable to force full reload (to make sure it's displaying the latest question from the database; these are updated manually using email).
Unfortunately the system is on a wireless connection that occasionally drops. As a result, when a student hits the switch input, a 'no Internet connection' is displayed and then sits there until I remote in and hit refresh.
My question is this:
I'm looking for the best workaround for this dropping connection. I'm not fussed if some entries are not submitted to the DB when the connection is down (it is informal and not totally accurate after all), but I'd always like the cycle of hit a button -> thank-you page displayed -> redirect to question (with check for new question if connection OK, else display previous question) to be consistent.
I'm assuming I somehow need to have both the question and thank-you loaded in one page and have no errors thrown up if submission fails, but I don't know how to proceed.
Many many thanks, Mike
On the first page, when they select any of the choices, have a simple div the size of the window pop up and cover the whole page so it looks like another page. Write an AJAX script (in the HTML itself) which executes in the background to submit the data. If the internet fails, the AJAX probably will fail, but since the script for the popup is local and has loaded with the HTML already, it should still work.
I'm implementing a twitter like news system on my website. It loads all news items on page load with an ajax call fine. But how do I show a new item without having a trigger like a page load or a click on something? So when a new item is added to the database, It should automatically be added to an open page, like an auto-update or something.
you can look into
ajax polling
reverse ajax
comet
server polling
here is a useful link http://www.zeitoun.net/articles/comet_and_php/start
edit
you can achieve the effect by using jquery alone below are some useful links
http://jquery-howto.blogspot.com/2009/04/ajax-update-content-every-x-seconds.html
Timeout jQuery effects
If you don't have an event, you have to generate one. A common practise to archive this is to have a timer running on the client/browser which fires an event in certain intervals to generate ajax requests.
Here are a few jquery plugins which might help you:
http://plugins.jquery.com/project/timers
Some SO posts which are in a similar direction:
Use AJAX to watch SQL database for changes
jQuery - If a database is updated, update the page
Sending notification to the user on database change
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.
Preamble to scope my question:
I have a web app (or site, this is an internal LAN site) that uses jQuery and AJAX extensively to dynamically load the content section of the UI in the browser. A user navigates the app using a navigation menu. Clicking an item in the navigation menu makes an AJAX call to php, and php then returns the content that is used to populate the central content section.
One of the pages served back by php has a table form, set up like a spreadsheet, that the user enters values into. This table is always kept in sync with data in the database. So, when the table is created, is it populated with the relevant database data. Then when the user makes a change in a "cell", that change immediately is written back to the database so the table and database are always in sync. This approach was take to reassure users that the data they entered has been saved (long story...), and to alleviate them from having to click a save button of some kind.
So, this always in sync idea is great, except that a user can enter a value in a cell, not take focus out of the cell, and then take any number of actions that would cause that last value to be lost: e.g. navigate to another section of the site via the navigation menu, log out of the app, close the browser, etc.
End of preamble, on to the issue:
I initially thought that wasn't a problem, because I would just track what data was "dirty" or not saved, and then in the onunload event I would do a final write to the database. Herein lies the rub: because of my clever (or not so clever, not sure) use of AJAX and dynamically loading the content section, the user never actually leaves the original url, or page, when the above actions are taken, with the exception of closing the browser. Therefore, the onunload event does not fire, and I am back to losing the last data again.
My question, is there a recommended way to handle figuring out if a person is navigating away from a "section" of your app when content is dynamically loaded this way?
I can come up with a solution I think, that involves globals and tracking the currently viewed page, but I thought I would check if there might be a more elegant solution out there, or a change I could make in my design, that would make this work.
Thanks in advance as always!
I wanted to follow up here, just in case anyone was interested. Turns out that my question was unnecessary.
Because I have my code set up to save the entered information in the change event for the input element, and since the change event only fires when the element in question loses focus, then if the user clicks anywhere else in my web app interface, that fires the change event for the input, and the data is saved.
The only exceptions are if they refresh the page, or they close the browser, but both of these events do result in an onunload event, meaning I can bind my save data function to that event and handle those cases.
So everything works as I hoped it would, and my confusion arose from a misunderstanding of when the change event would fire.
AJAX is normally overkill for site navigation. Unless there is a compelling reason to use AJAX , I would just make your navigation menu use good old links instead of AJAX calls.
AJAX is used to keep the user immersed in an application, without seeing the flicker, etc. of a full page refresh. However, if they are planning to navigate to another page, the full page refresh is expected (and therefore desirable).