how do you cache information using ajax, php, or jquery? - php

I'm trying to understand the use of caching data. i know a little bit about it. It helps data load faster because its stores the information in the browser?
If someone can help me understand this better, i'll be grateful. Also, is it possible to cache values from an input field and retrieve it or store it for later use? If so, can someone show me a sample of how it can be implemented in PHP, ajax, or jquery or guide me to a tutorial?
Thanks!

This season's fashion is to use localStorage for storing data on client's machine.
See for example this: http://php-html.net/tutorials/html5-local-storage-guide/

A cache is something which sits between a data source (database, hard drive, web resource, etc) and something that needs to access that data source. The idea is that accessing the data from the cache should be faster than accessing the data directly off the data source.
If you want to store text field values for use later, (without knowing more about the specifics of your setup), I think you're looking for a cookie.
When the user types text into the textbox, use javascript to set a cookie.
The next time the user visits the page, you can retrieve the things they have typed into the text boxes by using javascript to see if the cookie exists and if so, what's in them.
Note that this method will cache the data on the user's computer - not on your web server. If you want to store these values on the web server then you will need to write them to a file or database when the user submits the form, or use AJAX to send the value of the input form to your PHP back-end asynchronously, so it can store the value there.
If you can be a little more specific as to what you want to cache/store and why you think you should be doing it, then we can give you a better quality answer with some code examples.
Please describe exactly what your problem is, and what you expect the solution to do.
Edit: From your previous question it seems like you want some sort of auto-complete functionality. There are two-types:
1) Auto-complete what the user has previously typed:
When the user submits the form, you can do one of 3 things:
a) Store the text input in a database. When the user next visits the page, use PHP to embed the previous searches in the javascript (probably as an array). As the user types in the text-box, use javascript to display the auto-complete box. (Faster for the user, not so practical if you are expecting to store a huge amount of previous inputs per user)
b) Store the text input in a database. When the user visits the page, use AJAX to retreive the most likely match as they type. (Slower for the user, but better if you're expecting lots of saved searches per user)
c) Store the text input in a cookie. When the user submits the form, save the input in a cookie. You can either store multiple searches in multiple cookies, or 1 search in 1 delimited cookie. Note that the maximum size for a cookie (including it's name and other details is 4K, so you should keep it's body under 4000 bytes).
NOTE: If configured that way, the browser should automatically auto-complete what the user has previously typed. The only reason you would want to implement this type of auto-complete yourself is if you want some sort of cross-browser or cross-system functionality.
2) Predictive auto-complete like when doing a Google search.
This method essentially works the same as 1b. You will have stored in your database a list of previous or suggested search terms. As the user types text into the input field your AJAX request will fetch the most likely candidate for what the user is searching for.

It depends. You can cache images, css, js almost everytime because it is always the same. You do not need to do anything, they should cache automatically.
You can also cache GET and POST responses, but that's a bit responsible. You have to know what, when and how often should you flush it.
To turn on cache on GET requests by jQuery alone, use
$.ajax({
'cache':true,
'url' :'ajax.php',
//and more parameters
});

Related

Alternative to using $_SESSION variables to solve multiple tab issue

I started writing a web application that stores certain user information in the $_SESSION variable. Usual stuff - user_id, username etc.
I then started using the variables to store certain navigation information. For instance, $_SESSION['organisation_id'] so that wherever the user is in the application, I can easily add 'organisation_id' to any table without having to parse 'organisation_id' across every page request (eg. index.php?organisation_id=456&var2=6 or anotherpage.php?organisation_id=456& etc)
All hunky dory until a user opens a new tab and starts navigating to another organisation so hence creating a new $_SESSION['organisation_id'] value and creating an epic fail on the original tab.
The only solution I can think of is to go back to putting organisation_id into every form and navigation element within the application but yeesh, I'm thinking there must be a more elegant solution.
Normally, I find everything I need on StackOverflow but the answer to this question still eludes me!
"The only solution i can think of is to go back to putting organisation_id into every form and navigation element within the application but yeesh, i'm thinking there must be a more elegant solution."
No there isn't.
Maybe you can check if $_SESSION['organisation_id'] exist, and if so you can write new variable in session with different name, and so one.
Currently there is no way to solve the problem. But to avoid a similar task in the future, I would suggest split up all your files into different includes.
So even if you have to add a couple of variables to the entire site, you could modify 1 file and get it done than doing the whole thing again.
I think this is a logic problem. The session represents a state for the user. This is because HTTP is a stateless protocol in it's essence (it don't know who is who, just undersdants requests and responses).
So the organization_id is a state. If a user can login to just one organization, you just store this in the session var like you did and use it. If the user logs out and in again with another organization_id, it makes sense that only the last one remain available.
If your application has to support multiple organization_id's, you should reflect that logic in your session handling, saving an array of organization ids for instance (instead of just one). But then you have to change your application to allow the user to navigate from organization to organization, etc. There's no point in letting the user be in two organizations at once if the screen just shows one of them.
you can store the value into session during onblur of that username, etc and you can get it before you clicking the next tab
(i.e) using Jquery/Javascript u can get that value of username, etc while onblur and store it in session.
You can resolve this by simply moving the data you currently put into the $_SESSION array into a sub-array within $_SESSION, so that you can store multiple sets of data at once in the session.
It would end up looking a bit like this:
$_SESSION[organisations] = array(
'456' => array('organisationID'=>456, 'otherdata'=>'blah'),
'678' => array('organisationID'=>678, 'otherdata'=>'blah'),
...etc...
);
This will allow you to keep the data for multiple orgs in the session data at once, so you don't have to load all the data every time.
But yes, you will need to send the relevant organisationID with every request, so that your code knows which element of the session data to work with. You can't really work around that. Every request will need tell PHP which orgID to work with.
The down-sides here are that by storing all that data in the session, you're using a lot more memory for your session data, so if there's a chance that the user will browse a lot of organisations during a session, I would advise limiting the size of $_SESSION by dropping data that hasn't been used for a while.
The other down-side is that if this is a multi-user system, storing the data in session means that it will be unaware of any updates made by other users. If you were to load the data fresh from the database on every request, yes it would create more work for the DB, but it would ensure that the data given to the user was always up-to-date.

Adding multiples of an item to a form, without javascript?

Thanks everybody. (For some reason I couldn't up vote answers, so everyone wins today :] thanks again!)
Complete php and javascript novice here, apologize up front for anything half-witted.
I have a portion of a user's profile in which I'd like the user to be able to add additional items of the same thing, with slightly different conditions.
For example, let's say it's favorite books. A fieldset contains some checkboxes for genre and an input text box for the title of a book. After the user checks a genre and fills in a title, they can add the book to their set of favorite books and then have the option to add another. When done adding books, they move on to the next fieldset, complete the form and submit.
How is this done? And more-importantly, is it possible without javascript?
Without JS, I understand this probably entails a lot of reloading of the page to add the items, regardless I'm more confused about how the $_POST data is handled, both before and after the submit.
Sorry for such an open ended question, really just looking for someone to point me in the right direction, as searching for this topic proved to be a bit difficult.
Thanks.
Some Clarification
I'm trying to develop an application that is as independent of javascript as possible. In that sense, I don't know if it's possible to add the new items with PHP alone. My sense is the fieldset in question could have it's own submit button, the action of which POSTS to the page itself (no DB interaction, etc), and variables like $book_genre1, $book_title1 are populated in the page. Then, the "official" submit is sent later, which actually adds the POST data, which contains the books array, to the DB. But I don't know if that is a safe procedure or good logic to begin with.
In reply to the above answer, if that is exactly what you need since I seem to have a different idea.
You simply store each addition in an array stored inside a session variable, and in each page load, parse the data into readable html.
$_SESSION['form'][] = serialized_form_data;
On each load,
foreach ($_SESSION['form'] as $form) {
unserialize_data_and_create_html();
}
add_new_form_element();
I'm assuming you want to show the user already filled forms so he can deal with them as he wishes.
This is a better implementation than what I thought of earlier. I wanted to implement a db version.
Sorry for the delay. I can't comment since I'm mobile (js issues) so I decided to edit instead.
You can simply use the $_SESSION['form'] for your inserts.
A simple foreach will work as well. However, remember to sanitize each value properly before inserting it. That's the key.
If you use prepared statements with binding, you have the advantage of clean input as well as better database performance.
What you're really asking is how to persist information between POSTs of the same form. The most common and effective way of doing so is to just use the inputs on the form. If you have information that shouldn't be displayed then use hidden input elements for them.
Note that storing information in the form like this is not considered secure since it can be manipulated and/or forged, so the next option is to store it in the session; since it is server-side only the cookie/session ID needs to be protected. The values can then be retrieved from the session in PHP after the POST has occurred.
Before you submit a form...there is no data to handle. Once a form is submitted data then is sent to the server in the form of an array.
(From php.net/manual/en/reserved.variables.post.php):
$_POST = "An associative array of variables passed to the current script via the HTTP POST method."
So a user submits some data to the server. Now that data is available to your scripts for use: Populate a database, validate the values before doing "x", write HTML to the client, etc.
I like where #frosty is going with his approach. It does potentially send multiple requests to the server, but it's also a very straight forward approach. A completely server-side solution.
JavaScript or the jQuery Library would allow you to accomplish a similar result, and post to the server just once - by simply hiding/showing populated fields, writing additional fields to the form dynamically (eg: After completing "book #1" the user can click "Add another" and JS writes an identical set of form fields all referencing book #2). Obviously, this approach will get more involved than a straight PHP approach. And you'll need a backup plan if you want to allow users with JS disabled to participate.
I would suggest you use javascript to handle the user adding multiple items. Check out jQuery (http://www.jquery.com) which is a fantastic javascript library that will help you do lots of great dynamic things.
Then once you have all of the information from the user, just once it all at once to your php and save it. For information about to access and use $_POST or $_REQUEST, you'll need to check out some PHP tutorials or pick up a book. That's fairly basic PHP stuff and too large a topic for this thread.

How to _Post combination of formdata and non-formdata to php

I have a form I am creating and I would like to send information, not just from the form itself (easy enough to do with $_POST), but also generated information that corresponds to form data but is not visible to the user.
I could create a hidden input to put the data in, but I wonder if there's a way to do it that doesn't seem so hackish :)
(it's to submit a number of items, some new and some edited, I have a variable that increments for the edited ones but not the existing ones, and I need to be able to separate them out on the other end)
You're trying to maintain state across HTTP requests...
In any case you'll have to create a temporary variable server side. Something in the $_SESSION variable. There's not safer place to put data, primarily because only the developer can access this variable.
The disadvantage of this approach is the developer will have to start maintaining sessions.
I see nothing particularly hackish in using hidden fields. If your concern is about security (you don't want that the end user is able to tamper with the data) you'll have to use some sort of persistent server-side storage such as a database or a PHP session. Whatever approach you choose, make sure your app doesn't break when the user opens several tabs.

Passing data from page to page in PHP

Well, I have a new project, and I've not done anything like it before, but so far so good. I am in need of having to pass some data from one page to another, and there is no limit to the amount of data that gets passed.
At first, I was thinking of POST-ing it, and then when each page loads, just grab the POST data, and store it in an array, but to me that sounds a bit too over complicated or something for what I want to do.
Then I thought about HTML5 and localStorage, but since there is a limit on localStorage, and the fact that the majority of users browsers still don't support it yet (that is, the majority of my clients customers browsers), that's a big no no, at this point.
So, now I'm all out of ideas.
Here's what I'm trying to do, it sounds pretty simple to me, yet I can't figure out how to go about it:
On any given page, there are a probably over a hundred links, each link represents either a name of a product or information about a product, if they click on of these links, and then move off to another page, then the information about what product name they clicked on would follow them to that new page, and then the same thing happens on the new page, if they click on one of those links again, then new info will be added to existing information, and passed on to whatever new page they visit.
I guess you could say that it works almost exactly like a shopping cart, whereby if a user Adds to Cart, their Cart, and all data inside it follows them right to Checkout.
I'd appreciate any help at all?
You are looking for sessions. With the limitation that you shouldn't be storing unlimited amounts of data in a session file, either; better create a temporary file that is named after the session ID, or store the data in a database.
Alternatively, you can also implement a custom session handler.
Either way, Sessions are the standard way of persisting state across page requests for the same user.
You could store the data in a session, or even in a database table (if there truly is "no limit").
For more information on sessions, see Session Handling in the PHP online docs.
I think you really want to use a database for this purpose. Each page pulls the data out of the database as the user clicks through. I guarantee you that for a hundred or so objects from the database, the time to access the database from each new page is an order of magnitude smaller than the round trip HTTP time from the user's browser.
what you are looking for is php sessions.
Yes, for your purpose you should use sessions, I'm agree with others users.
But keep in mind that: sessions expire. If you were looking for a persistent solution, you can store your PHP objects (vars, array, object instances, etc...) using the serialization and unserialization. Using this method you can store your objects in plain text everywhere (eg. DBMS) and restore them at any time. If you're working with objects you can also use the magic methods __sleep() and __wake().

How to use sessions in place of a querystring

Using PHP.. I have a small app that I built that currently uses a querystring to navigate and grab data from a database. The key in the database is also in the string and that is not acceptable anymore. I need to change it. I would like to hide the db key and use a session in place of it but I'm not sure how to do that. In fact, there are also other variables in the query string that I would like to use sessions for if at all possible.
page.php?var1&var2&id=1
This is what my string looks like. I am looping through the results in the database and have given each row the id so that when the user clicks the row they want, but I'm not sure how I could do this with a session.
Does anyone have any ideas?
Thanks
EDIT:
I'm developing an email type system where senders and recipients are getting and sending mail. Each piece of mail that is stored on the server will have its own unique key. Currently, I am using that number to retreive the message but the problem is that I don't want people to change the number and read other people's mail. I can probably use a GUID for this or even some sort of hash but I really hate long query strings. I was just thinking it would be so much cleaner if there was a way to "hide" the id all together.
UPDATED (Again ... Yeah, I know.)
Allowing access to a particular set of data through a $_GET parameter is much more accessible to any user that happens to be using the application.
UPDATED
For storing a private record key, you are probably going to want to use post data, and if you really want it to look like a link, you can always use CSS for that part.
Honestly, the best way to stop people from reading other people's mail is by having a relationship table that says only X person is able to access Y email (by id). That or have a field that says who is the 'owner' of the email.
The fact is that users can still get access to POST parameters, and can easily forge their own POST parameters. This means that anyone could realistically access anyone else's email if they knew the naming scheme.
In an ideal system, there would be a Sender, and a Recipient (The Recipient could be comma separated values). Only the people that are on one of those columns should be allowed to access the email.
How To Use Sessions (From Earlier)
First start off with calling session_start(), and then after that check for variables from previous scripts. If they aren't present, generate them. If they are, grab them and use them.
session_start();
if(!isset($_SESSION['db_key']))
{
$_SESSION['db_key'] = // generate your database key
}
else
{
$db_key = $_SESSION['db_key'];
}
Sessions are stored in the $_SESSION array. Whenever you want to use $_SESSION, you need to call session_start() FIRST and then you can assign or grab anything you like from it.
When you want to destroy the data, call session_destroy();
Also check out php.net's section on Sessions
Your question isn't too clear to me, but I understand it like this:
You need some variables to decide what is being displayed on the page. These variables are being passed in the URL. So far so good, perfectly normal. Now you want to hide these variables and save them in the session?
Consider this: Right now, every page has a unique URL.
http://mysite.com/page?var1=x&var2=y
displays a unique page. Whenever you visit the above URL, you'll get the same page.
What you're asking for, if I understand correctly, is to use one URL like
http://mysite.com/page
without variables, yet still get different pages?
That's certainly possible, but that means you'll need to keep track of what the user is doing on the server. I.e. "user clicked on 'Next Page', the last time I saw him he was on page X, so he should now be on page Y, so when he's requesting the site the next time, I'll show him page Y."
That's a lot of work to do, and things can get awkward quickly if the user starts to use the back button. I don't think this is a good idea.
If you need to take sensitive information out of the URL, obfuscate them somehow (hashes) or use alternative values that don't have any meaning by themselves.
It completely depends on your application of course, if the user is accumulating data over several pages, Sessions are the way to go obviously. Can you be a bit more descriptive on what your app is doing?
Edit:
but the problem is that I don't want people to change the number and read other people's mail
If your primary concern is security, that's the wrong way to do it anyway. Security through obscurity is not gonna work. You need to explicitly check if a user is allowed to see a certain piece of info before displaying it to him, not just relying on him not guessing the right id.
There are some examples on how to use $_SESSION on php.
Registering a variable with $_SESSION
The issue with using sessions for using it in place of S$_GET or $_POST is that you need some way to read the user's input so that you can store it in the session, and you need a way to trigger a page refresh. Traditional means is via hyperlinks, which defaults to GET (unless you use Javascript) or forms, which defaults to POST.
Maybe ajax will help you here. Once the user has enter info into a form or a checkbox, use JS to send a request to insert the info to the PHP and send info back, whether it is to refresh the page or to fill a with content.
Hope this helps

Categories