You load a page display.php with a lot of ajax content in different areas of page.
A user clicks inside the page and some part of ajax content changes. Now when a user
clicks the reload button on the browser it will loose the content loaded from ajax requests.
How do I retain all information loaded by ajax? Much Thanks.
You have two options:
store information in localStorage (in JavaScript),
store information on the server, eg. using server sessions,
plus one additional possibility (if applicable in your case):
use pushState and onpopstate to support URL changes without requests to the server (alternatively solve it with onhashchange),
You may also use location hash.
Write something on the location hash as an ajax call runs. So when you reload the page, the on $(document).ready you may read that hash and load the data again with ajax calls.
This approach has a point, you can share the url#hash as a link to that data with other persons. It's not dependent to your session or your localStorage.
Krister has it right. Store the changes in a session variable and have a recall function on $(document).ready that checks session variables. ;)
Related
I have a form on a simple web page that has a series of checkboxes. These options represent items that may be retrieved from a database upon clicking the submit button. In addition, there is a place to add an extra option to the page at the bottom. Here is what I am going for:
I would like to be able to add the new option using javascript, so that it show up quickly and seamlessly to the user, rather than having to send the request back to the server and add it server-side, then have the user reload the page. However, I also want to make sure that these added fields are preserved so that the next time I load the page, they show up.
Unfortunately, my code is proprietary, so I cannot post it here. I hope that people can help me this some ideas without having to actually see the code.
Thanks
When these checkboxes are added you don't want to go the server but when user presses submit you are anyways going to server, so at that time you can persist this information about new checkboxes on server.
Another option is to call to server asynchronously using AJAX to update the server about the state change.
If you still want to store the changes server-side, you can do so quietly in the background.
Just use XmlHttpRequest(), together with a PHP script.
You can use the HTML5 local storage API to store your changes.
localStorage.setItem('favoriteflavor','vanilla');
If you want session related information to pass thru multiple requests, you can either put the data in a cookie, or with php you can use sessions.
http://php.net/manual/en/features.sessions.php
I was going to ask about how to implement sessions in JS,I found few functions that can be used like this example I found :
String exforsys = request.getParameter("test");
session.setAttribute("test", exforsys);
And then just use session.getAttribute( exforsys);
But no response, I guess it's only used in servlets or something.
Anyway, I decided that maybe someone has an alternative way other than just use sessions, what am trying to do is click on a link in one page and depending on which link was pressed I will load different information.
Since its a onclick function, I'm stuck with JS!
So I need to pass this information to the second page, cookies works well cause it can be handled with both PHP and JS easily but some computers deletes cookies and that wouldn't be nice!
Any suggestions or other ways I can reach what I want but with out using sessions?
Sessions are server variables. Thus cannot be used by JavaScript.
However, you can retrieve the session variables, through ajax request.
Script (jQuery)
//This portion will be triggered once the DOM is loaded and is ready
$(document).ready(function() {
$.post("getsession.php",
{ "variable" : "yourneededsessionvariable" },
function(data) {
//data contains your session data
}
);
});
PHP
//getsession.php
<?PHP
session_start();
echo $_SESSION[$_POST['variable']];
?>
Use local storage or client controlled cookies.. Sessions uses server-controlled cookies. Cookies are just small files that resided on the client.
A session handle is stored in a cookie. If cookies are not accepted, the server will add the sessionID to the URL. If you do not have cookies, you cannot persist anything except in the url.
Why does "onclick" stop you from using sessions? You can ajax things to the server and add them to the session onclick
A session generally means "Some data stored on the server and associated with a user via a token stored in a cookie". You can't do that with client side JavaScript (for obvious reasons).
You could store data directly in a cookie.
If you are willing to sacrifice wide browser support, then you can get increased storage by using one of the client side storage mechanisms introduced by HTML 5 and Friends.
maybe someone has an alternative way other than just use sessions,what am trying to do is click on a link in one page,and depending on which link was pressed I will load different information.
Just link to different pages.
some computers deletes cookies and that wouldn't be nice
If they delete all cookies, then a session isn't going to work either.
Append the data you want the next page to get on the query string.
123
456
Then on foo.html you can inspect location.href to see what was passed in. THere is no need for cookies here.
PHP is a server scipring language while javascript is client end language
you cannot literally make sessions in javascript
Why not just use request parameters? i.e. http://yourserver.com/page.php?link=1
So I am very new to this concept.
So why not go headfirst :) Some things I don't understand;
What happens if js is disabled?
If using mysql databases (ie; checking forms and such) why not just use php?
To confirm what others have said, disabling Javascript will also disable the AJAX call. After all, AJAX stands for "Asynchronous Javascript and XML".
To address why you can't just use PHP, there are some things that just can't be done without it. PHP is great to load the page with the initial information, but after the page is loaded, it actually requires the page to be reloaded to load something else. AJAX allows you to get around this hassle.
For your example of form validation, AJAX can be used to validate the information while the person is filling it out. Otherwise, you are required to reload the page each time someone fills out another field in the form.
Another example is from a project that I have worked on. The form required a zip code and would load the appropriate city and county based on the inputted zip. Using strict PHP, I would need the client to download the entire zip table embedded in the HTML/JS (which would add another 100k at least to the download).
Using AJAX, I can get around this. The user can input the zip code, which triggers an AJAX call that downloads the few rows that I need (this will be less than a few hundred bytes, for comparison).
[Edit:] Also, a tip because you said that you were new to AJAX. If your dealing with some form of authentication (logging in, etc.), remember to validate the user on the AJAX pages themselves. Otherwise, tricky users will be able to access sensitive information for your database.
Ajax just adds to the user experience and allows a web application to feel more like a desktop application to users. So they can delete a record and stay on the same page without reloading, you just let the record disappear.
And remember to validate on the server-side, even if you validate on client-side. Your weakest at your client-side as someone can easily just submit the values straight to your script so ALWAYS check on the server-side and do client-side if you would like to add some nice effects etc.
But you will always need to keep in mind that there are people out there who have javascript disable be it a security policy or just because their paranoid. So when you don't have JS enabled you javascript and AJAX requests won't work. So while developing you will need to make sure that if javascript is not their to do the operation that the form is submitted just like a normal HTTP form, this will allow all those paranoid people to also use your application :D.
OR you could always just deny access to those who don't have Javascript enabled but that's not very nice ... So if you want to check if they have javascript enabled checkout - http://www.w3schools.com/TAGS/tag_noscript.asp - for a example.
AJAX is a Javascript client based technology. If js is disable it simply doesn't work.
Php is a server based technology.
In Php you write pages that are dinamically built by the server. Once built they are sent as html to the client.
Using javascript (and Ajax) you can call the server just to request some datas (hint: look at JSON) or just a little html snippet which is plugged in the current page directly by the browser without requesting a full refresh from the server.
With js and AJAX you can achieve a very rich client experience without reloading a full page every time.
I believe nothing will happen if js is disabled. You need js to grab the data.
If you want to use mysql databases, you can use js to access a php script, which can then return any data gathered from a database, rather than doing it in the page.
AJAX is a way for Javascript (client side) to access PHP/ASP/Whatever serverside language you are using. This means, that if you have an PHP script for getting some data from your MySQL database, and want to run that script when the user clicks some random button, AJAX can do that (async)m and you wont have to reload you page to execute the PHP script.
If Javascript is diabled, AJAX won't work.
From a security standpoint, can someone give me a step-by-step (but very simple) path to securing an ajax call when logged in to PHP?
Example:
on the php page, there is a session id given to the logged in user.
the session id is placed dynamically into the javascript before pushing the page to the client.
the client clicks a "submit" button which sends the data (including the session id) back to the php processing page.
the php processing page confirms the session id, performs the task, and sends back data
I'm stuck on how (and whether) the session data should be secured before sending it through an ajax request. I'm not building a bank here, but i'm concerned about so many ajax calls going to "open-ended" php pages that can just accept requests from anywhere (given that sources can be spoofed).
PHP can get the session data without you having to send a session ID via javascript. Just use the $_SESSION variable. If you want to check if a session exists you can just do
if(isset($_SESSION['some_val'))
//do work son.
You'll need to use JavaScript to asynchronously pass user input back to the server, but not to keep track of a session.
Don't send your session data with javascript.
You don't need to (in most cases).
Just post the data with javascript and let PHP retrieve the session data from... the session.
Depends on how you setup your session data.
One simple example would be you have a session called username.
When PHP gets the request from javascript you can do: $_SESSION['username'] to retrieve the sessiondata.
This is a very simple example just to show how it can be done.
As noted above, you don't need to send any session identifiers out with your javascript, to the server an AJAX request is the same as any other request and it will know your session just fine. So basically, just don't worry about it, it's already taken care of.
It's another part of your question that worries me.
i'm concerned about so many ajax calls going to "open-ended" php pages that can just accept requests from anywhere
It worries me too; you shouldn't have any "open-ended" PHP pages hanging around at all. Every public .php script should have authentication and authorisation done. The easiest and most maintainable way to achieve this, IMHO, is to have a single controller script (e.g. index.php) that does authentication and authorisation then sends the request to an appropriate controller. Aside from this controller, all other scripts should be outside the document root so that they cannot be called directly.
This means that you only ever have to worry about authentication and authorisation in one place; if you need to change it, it only changes in one place. It means you don't need to worry about accidentally leaving some executable stuff in some library PHP file that's not meant to be called directly. It means you don't need to shag around with mod_rewrite rules trying to protect .php files that shouldn't be in the doc root at all.
Working on PHP application, that uses DataTables (https://datatables.net) on several layouts.
Can I somehow reset all DataTable's filters and search data, after end user logged out from application? In other words, to clear all cookies that DataTables library created, if it's possible with PHP functions..
Main idea is to reset application to it's main state after user is logged out from application.
Thank you in advance!
The documentation says: (https://datatables.net/examples/basic_init/state_save.html)
The built in state saving method uses the HTML5 localStorage and
sessionStorage APIs for efficient storage of the data.
It means you cannot reach it with PHP.
However you can change the storage of filter parameters to cookie or server side.
Alternative options of using cookies or saving the state on the server
hrough Ajax can be used through the stateSaveCallback and
stateLoadCallback options.
You should write code which:
- save the filter parameters to cookie what you can remove on logout with PHP
or
- save the filter parameters to database via AJAX and you also can remove it on logout with PHP
example is here:
https://datatables.net/reference/option/stateSaveCallback
In case anyone out there is interested in a solution to this:
As some people rightly pointed out, there's no way to delete localStorage from PHP because PHP works only on the server and localStorage is client-based.
However, a way to achieve what OP wants is make sure that the page shown after logout has the JS needed to delete localStorage. For example, say that after logout, the user gets redirected to comebacksoon.php; what you need is to make sure that in the html of this comebacksoon page, you include:
<script>
localStorage.removeItem(keyYouWantToDelete);
</script>
It should be noted that if the user closes the window before comebacksoon.php is loaded, localStorage won't be deleted, but this approach has worked for me in most cases.