Is there a common name for this "session locking" method? - php

On one of my pages I have users queue up search terms to be to queried from a 3rd party API. As they're building the queue, my site is making the queries in the background (through ajax) so I can cache the responses, saving them time when they submit. I store a session variable $_SESSION['isloading'] as true during the time that the background queries are running, and its false when they're done.
When they submit, the results page waits for $_SESSION['isloading'] to be false before querying the cache for result. Meanwhile they're shown a progress wheel.
Is there a name for this technique of using a session to locally "lock" a user before proceeding to the next step in the code? I came up with this approach on my own and was wondering if it is a common (or good) solution to this problem, and is used elsewhere.

Putting it in $_SESSION will be a wasted effort. Been there, done that and it didn't work out.
You will be much better off if you provide your "search query string" in as a $_GET variable for your XHR ( marketing people call it - Ajax ).

Off the top of my head, this sounds a little similar to the way some older forum software performs forum searches in the background, and the visible page does a repeated refresh until the background search is complete.
I don't think there's a name for it; I'm also note entirely convinced that it's a great solution. As stevecomrie pointed out, you're going to run into difficulties with concurrency (unless the session variable's name is unique per search query).
I'd instead recommend an XmlHttpRequest (as teresko points out, it's not really called "AJAX", ugh!) and you can handle the "waiting" quite simply with Javascript.

I asked about this on IRC (Hat-Tip to ##php on freenode), and they suggested I just make the search form and search results one page. Then, when they're done entering their searches the view would change rather than submitting to the next page. This would remove the necessity of keeping track of an 'isloading' state. This seems like a better approach to me, are there any problems with it?

Related

Display a tip to a user once

I was working on a web app and thought it would be awesome to give the user a tooltip or side note on a new feature that has been added.
This would be similar to the way Google or Facebook displays their tips about updates.
I had an idea of setting a cookie (or session variable) to say that the tip has been viewed and not display it again, but this would be running an unnecessary if statement on every page load.
Here is what I have so far:
if ($_COOKIE['displayTip'] != 'no') {
echo "tip";
}
Are there better ways of doing this, or is one if every page load worth it?
A single if - especially if it is not checking a database - is no problem. Don't worry about it, you can waste more CPU time with other things. If it adds functionality its fine.
One thing you could do is to have the logic on in the Browser (JavaScript) only. This has the advantage you do not have to generate two different pages. This might be beneficial for caching. In JS you can also access cookies to make that seen flag persistent.

HTTP request via AJAX or form-submit. Which one should I choose and why?

I have a PHP page with a simple form. One input text field & a button. Input text field accepts user queries & on button click an HTTP GET request is made to the server & the result has to be shown back in the same page containing the form. That's too simple to do. I can do this in two ways. One is AJAX & other one is the good old sodding form-submit method.
My question is simple- Which method should I use? Since both of the roads lead us to the same place, which one should I choose to travel?
First of all, let me talk about form submit method. I can use <?php echo $_SERVER['PHP_SELF'] ; ?> as the action of the form for submitting the values of my form to the same page. Once I store those values into some random variables, I can make a GET request & obtain the result & show it to the world. This method is easy to use. Happy Down Voting to all of you.
Or I can make a GET request using AJAX and jQuery or JavaScript or whatever you wish to use & obtain the same result as in the previous case. Output is same. Only the mode of execution is different.
So which one is better? Which one fetches result faster? And why should I use that? Is there any difference? GET, POST, PUT or whatever- it doesn't really matter. AJAX or form-submit?
There shouldn't be any significant, genuine speed difference between them.
The Ajax approach will load a smaller amount of data (since you aren't loading an entire HTML document), but by the time you take into account HTTP compression and the fact that (if your system is sensibly configured) your dependancies (images, scripts, stylesheets, etc) will be cached, it won't be significantly smaller.
By using JavaScript to create a loading indicator and not refreshing the entire window in front of the user, you can create the illusion of a faster load time though. So if feeling faster was the only concern, then Ajax is the way forward.
Using JavaScript, however, is more complicated and slightly more prone to failure. The consequences of failure states are more severe because, unless your code detects and does something with them, the user will (not) see it fail silently. For example, if a normal page load times out because the user is on a train and went through a tunnel, they'll see an error page provided by their browser suggesting that they refresh and try again. With Ajax, you need to write the error handling code yourself. This does give you more flexibility (such as allowing you to simply try again a few times) but the work isn't done for you.
The other consequence of using Ajax is that the address bar will not update automatically. This means that the results won't be bookmarkable or sharable unless you do something explicit the make that possible. The usual way to do that is pushState and friends, but again, it is more work.
You should also make the site work without JavaScript so that if the JS doesn't run for any reason then the site won't break completely. If you use pushState then you have to do this for the URLs you are setting the address bar to point to to be useful.
The short answer: Use a regular form submission, then consider layering JavaScript over the top if you think it will give your visitors a worthwhile benefit.
I Should stick to an Ajax request when possible.
This because you then don't really have to load every single item on the page again ( like all the images, menu and so on ). You can just give the relevant HTML back and JQuery can place it inside the relevant holder.
But that is just my humble opinion...
If you have to retrive simple data from server without reload the page my advice is use jquery .get o .post
also it provides you a very large API that allows you to reduce your programming time.
http://api.jquery.com/
obviously the execution time increase but in my experience the user cant fell the differce with a simple ajax request.
so in my opinion if jquery allow you to obtain the results, this is the best solution because halves your work time!
See the edited one it may help you.
I think that AJAX should be used for displays updates and form submissions should be done via a page reload. Reasoning?
When submitting forms, you are telling the application to do something. Users tend to want to feel that it was done. When a page doesn't reload, users are often left wondering "Did that work?". Then they have to check to make sure what they did was right.
but when you are displaying a table or something, and the user says to "display x data....now x1 data" for instance, they aren't "doing" something (creating new entities, sending emails, etc). So AJAX can provide a nice user interface in this case. Page reloads would be annoying here.
In conclusion, I think form submission should be done via page reloads (let the user see it working), whereas display updates should use AJAX (prevent annoying page reloads).
Of course, this is a preference thing. Some of my company's applications use AJAX all over. But those are the applications that are the most difficult to maintain and debug. ;)``

Caching and session variables (PHP, MySQL...)

Apologies in advance for the lengthy post, just trying to explain the situation clearly.
I've created a PHP-driven website for searching a big (millions of records) MySQL database of people. On the search page you have your usual form for search criteria. Due to the way the people often use the site, the search criteria are saved into session variables so that if the search page is reloaded the previous criteria remain in the form fields (there's a button to manually reset the criteria, of course). This in itself works fine.
I also have two language selection links that store the language selection in a session variable (making the page header load an appropriate localization file), and as above, this in itself also works fine.
What's problematic is that when a user gets the search result, a list of people, and wants to open up detailed info on a person (thus going from search.php to info.php) and then wants to go back to the people listing via the back button, it takes too long to reload the previous page as the page re-sends the MySQL query etc, instead of going back to a cached page. It can take even 5 seconds or more sometimes as the queries produce up to 5000 results - but even say, 200-500 results takes long to reload because the database itself is big and not the fastest in the world. And limiting the number of results isn't really practical.
The obvious solution at first glance would SEEM to be enabling the browser cache. Which is exactly what I did via PHP header and pragma controls. And all seemed well, as going back to the list was basically instantaneous. However, I realized that enabling the cache means the updated session variables don't work. New search criteria doesn't properly replace the old ones when reloading the search page after having been to a different page, and even though you select another language, pages open up in the language you previously were using, because that's the way they were cached! You can force the language to update via F5, but that doesn't seem to help the search criteria much. But even if it did, F5-spam isn't really an answer, it needs to work automatically.
So long story short, how do I make the search result list open quickly without making session variables useless? Or will I simply have to make do with sluggish page loads when using back button, thus annoying users? I really don't want to open the info.php in a new page, either.
Have you considered caching the database results on the file system? I have found the Zend Framework caching class to be very easy to use. You can use any information you want, to differentiate cached results from other cached results. So the caching can be as fine grained as required.
http://framework.zend.com/manual/1.12/en/zend.cache.introduction.html
You don't need to use the whole of Zend Framework to use the class. You can use it on its own.

PHP/JavaScript - detect which users currently have the page open

I want to make a page that will show all the users who are looking at that page right now. Ideally, a database would store which users are on the page and websockets would be used to update when users enter and leave.
The problem is that I don't know how to tell when users are viewing the page. I was thinking that I would be able to tell when they arrived and when they exited and add/remove accordingly. It's easy to tell when they arrive; however, it's difficult to tell when they leave - especially because users might do something like open multiple tabs, close one but keep the other open.
What is the best way to do this? I am using PHP as my server-side language.
You can use the blur and focus events on the window to toggle a variable. However, IE does some quirks which you will need to work around.
As a fallback to not working focus events, you might add a mousemove handler to the document. This might also throttle an automatic timeout which detects the loss of focus just by the fact that there was no user interaction for a specific period of time. However, you will never be able to detect a distracted user that has the site open but looks at something else...
To detect the window closing, you can hook on the unload event. This might be unreliable, but as you are using Websockets your server can easily detect a closed connection.
Well, one thing you could do, especially if you are using websockets is do a heartbeat/ping to the server every few seconds if you really wanted. If you don't get that heartbeat, you know they are not on the page anymore.... however, getting a response doesn't mean they are looking at the page, it would just mean that it is open, possibly in another tab. There is no way that I know of that will send a response to the server if the person loses focus on the page and opens another tab/window.
As Tim mentioned, Firefox and IE will run javascript in the background tabs, so there's no surefire way by simple polling to tell if the user is actually "looking" at the page or just has it open somewhere. Although I know of no way to tell if the user is actually looking at your page, a potential solution might be to bind polling to actions. So you might have some variable
var timesincelastaction=0;
var threshhold = 20;
Then
setInterval("timesincelastaction++",100);
Then
function keepAlive() {
if(timesincelastaction > threshhold) {
$.ajax(...tell the server you are alive...);
timesincelastaction = 0;
}
}
Then start thinking of actions like
$('a').mouseover(keepAlive);
$('div').mouseover(keepAlive);
$(window).scroll(keepAlive);
$(video).play(keepAlive); // okay this isn't a real one but you get the picture
So then you just brainstorm on everything the user can possibly be doing on the page that requires their attention and use those as your benchmark.
This seems a little intense I know, there's probably some nice ways to optimize it. Just thinking out loud. Curious to see what others come up with.
Every time one of your PHP scripts run, some user or entity has requested to view a page on your site (this usually occurs every time your script runs).
It is more challenging to detect when a user has left your page, which is why most online indicators are simply a timeout, i.e. if you have not been active on the website in the past 5 minutes, you are no longer considered online.
You can get information about the user who requested the page with variables like $_SERVER['REMOTE_ADDR'] or if you already have an authentication system you should be able to pull a users username, store this info in a database with the username/ip as a unique key with a timestamp, and simply not count them as online if their timestamp is older than 5 minutes.
You could probably use jQuery- ajax, unload and load. The ajax request will trigger on load telling you that they are viewing, and trigger on unload telling you they are no longer viewing. The rest is left to you to figure out because it sounds like you already have a grip on it.
Note. same result should be achievable in plain JS. Such as, onunload. Google will find you the rest.

Forwarding POST data

I've got a website that has a form that the user can type in. I want it to be the replacement for a 3rd party website (Autotask) form with the same fields. Normally I'd just have the action in my form go to where the 3rd party's form points and then have all the same id/name values for my own fields, but there are several problems with this:
Autotask's forms aren't just simple muli-field forms. They import at least 15 Javascripts that make something magic and unidentifiable happen, and they are incredibly difficult to read and understand. So that causes two problems, one that the form takes a very long time to load (5 seconds or so for 4 fields), and two is that if Autotask changes anything at all I'll need to redo the whole form (very tedious and crapshoot-y, and I already have needed to do it twice).
In order to make the load time more transparent, I put my copy of the Autotask form within an iFrame. That way the rest of the website can load separately from the expensive number of scripts I've got to include with Autotask's logon process.
Ideally what I want to be able to do is to just have those 4 fields on my site with whatever name and configuration I want, then send that POST data to my own PHP script, which will automatically (and transparently) submit that data directly through Autotask's forms in the proper fields. If I need to make the id/name match, that's okay. I can use HTML, Javascript, and PHP on this site.
EDIT:
Autotask has built-in GET handlers for their logins. You'll notice that you have a client ID at the login (it will be the "ci" variable in the URL). If you send a GET request with the client ID there and variables for "username" and "password," then it Autotask's login page will immediately forward you to the client page, given a successful login.
I think a lot of people would advise against this in general, as you're kind of hacking the functionality of someone else's app. In this case I only advise against it because they (Autotask) have an outward facing API already. http://www.autotask.com/press/news_and_press_releases/071006.htm I think that you'd be better off just utilizing it and developing something that functions pretty well within the constraints of their system.
one really round-about way of doing it is have your page load a form with some generic id/names. have a php script that scrapes their page for the correct id/names, and the ajax them into your forms.
That way you avoid having the load time of iframing their content in, or scraping their page on your initial page load and they change the id/names you'll always have it up to date.
I could write up a big post that explains on this, but really I think this is a perfect time to let someone else's words do the work.
Autotask's forms aren't just simple muli-field forms. They import at least 15 Javascripts that make something magic and unidentifiable happen, and they are incredibly difficult to read and understand.
Sounds like anti-spam measures to me? If so, then they will probably change over time.
So: follow NateDSaint's advice!
As a follow-up, it turns out that with Autotask they have GET handlers so you can just send information via GET. Problem solved.

Categories