Facebook Game Function, Optimizin a Call, and Loading Bar - ajax

I am attempting to make a Facebook game and trying to replicate a common function that I usually find in many other Facebook game (a call to my website and illusionary image that is a loading bar).
The function should do the following:
User clicks on Button
Animated Gif Appears (Loading Bar)
Button Update User's Status
Animated Gif Disappears
Facebook Canvas page is updated
The code I currently have can be found at <dead link>
I am having trouble thinking of Step 2 and 4.
I need to optimize Step 5.
To clarify what happens on Step 5. I have Box 1 which has my stats. And Box 2 which has my points. I click on Box 1. This should update Box 1 with 1 points, and update Box 2; minus a point. (Clicking on Box 1, concurrently update both boxes)
I have successfully done this, but it is quite slow. I was wondering if there are alternative way that may be faster than what I am currently doing.
Script Updated with Mark-up. <dead link>
I've found a quick way to optimize the call. Rather than querying for data that I already have query, I will be using the first query to grab most of my data rather than querying it when I update.

It would help greatly to see the document markup (XHTML) where you have your elements and the calls to your javascript functions.
For steps 2 and 4 I recommend using the visibility attribute rather than display, or having the loading bar in an fb:js-string and using elem.setInnerFbml when you begin loading and once you have your response data, simply update it to the new content (you don't need an explicit loading_finish function in this case).
In your get_skillpoint function, you set parameters in an object and then you specify the action parameter again in the URL you are posting to as a URL query param - you may end up with one value overwriting the other, depending on how you access these values on the server side. I would recommend using different names for these two parameters if they are not the same. Also, why are you trying to send separate GET and POST variable sets? You should put everything in the POST and simply leave out the URL query string. I vaguely remember losing data that way in the past (vaguely, mind you).
If you can post your markup I'll update my answer with any light it sheds on the problem. It might be slow simply because Facebook isn't blinding fast when it comes to FBJS and AJAX. Also, FBML being returned must be preprocessed in the FB proxy before your app gets it, which adds a bit of lag; it's a bit faster to return JSON and just pull the data needed out of it, then place the appropriate pieces into an existing element or make use of fb:js-string.

Related

How do Big sites prevent the loading circle on tabs from showing?

Okay I do not know how to explain this to you, It may be just my internet, or maybe my site is slower, or they really have a technique for doing this.
If you visit Facebook, Reddit, Youtube, Twitter, and if you click on links or any actions on those websites, the url changes but the browser tab doesn't show any loading circle.
How do they do that?
I am pretty sure my website is fast enought and at times it loads even faster than the bigger sites, but mine shows the loading circle on the browser tab.
Okay so I found the answer. Here is the technique for changing the url without reloading the page.
Updating address bar with new URL without hash or reloading the page
How do I modify the URL without reloading the page?
I am still trying to figure out though how to redirect the actual page without reloading the entire page. I am guessing they are loading it via ajax or something similar upon url change. I'll update this once I figure it out.
Edit: I am currently working on this feature for my site. The technique is to use ajax to load the content based on the url. I'll update this thread more as I update my site with this feature.
Edit 2: Damn, you will probably face the same problem I had trying to detect the url change without using onhashchange. If so, here you go:
How to detect URL change in JavaScript
This literally took me 4 hours just to figure that one out.....
Edit 3: I have now integrated this feature on my site. You can check it at
Grandweb
It is quite simple, but lots of work in appending the content once retrieved via ajax. So here is the process:
I am using pushState(); to change the url without reloading the page.
var url = $(this).attr('href');
var split_url = url.split('/');
var new_url = url.replace('https://grandweb.net/','');
window.history.pushState("object or string", "Title", "/write");
Using 'mouseup' was a bad idea, I changed my mind.
I then have to trigger the first function using 'mouseup' to retreieve the content via ajax, and then listen to succeeding onpopstate() for the next ones, because some mouse actions such as Mouse 4 or Mouse 5 are bound to the browser's Back and Forward button, and does not trigger via 'mouseup'.
$(window).on('mouseup', function(evt) {
get_content();
}
window.onpopstate = function(event) {
get_content();
}
The first one is responsible for triggering the function on first try because onpopstate only listens only when the browser's history API is populated.
Using mouseup was a bad idea, basically, don't use it unless you really want to detect mouse action from anywhere on the document.
I instead use the anchor tags/links to trigger the first function for retrieveng content.
example:
<a class="dynamic_btn" href="website.com/post">Home</a>
then
$(document).on('click','.dynamic_btn',function(e){
e.preventDefault();
get_content();
});
Using onhashchange is possible IF you have hashes on your url. I do not use hashes on my url so basically onhashchange is useless in my use case, unless I do not know something.
After retrieving the contents, I append them via creating DOM elements to existing containers from the page.
This is much easier to do if you are planning to change few elements or containers in your pages. If you plan on doing this to change a full page layout, goodluck. It's doable, but it's a really pain in tha *ss.
Upon observing Facebook, I learned that they do not implement this technique in all of their links/features. It makes sense because this is harder to maintain most especially because most of the work here is being done client side. It is very nice though because the page doesn't load.
I have implemented it on a few 'essential' functions of my website such as the viewing of posts and returning to the homepage. I can implement it on the whole site, but I am still deciding on that. That is all, thank you very much for reading internet stranger.

Dynamically change address in the URL bar

Okay, I have seem similar questions around Stack sites, yet some of them were asked as far back as four years ago, so given the recent developments in HTML, jQuery and PHP, I'm convinced there are new workarounds.
Suppose I have a domain www.mysite.co.uk, which has an ajax that, once triggered, clears the default on-load content #0, and replaces it with content #1.
(This content can also be accessed by going to www.mysite.co.uk/1)
Then a user may trigger another ajax that will clear content #1 and populate with content #2.
This is where I have a problem. Because clicking the Back button will not send the user back to content #1 (in fact if there is no history, the Back button is greyed out).
What I want to do, is when user triggers an ajax that populates the page with content #3, I also want it to change the URL bar to www.mysite.co.uk/3, so this way the same content will load when the page is refreshed, instead of going back to the default content #0.
Hope this makes sense.
I know that www.asana.com do it, but not sure how.
I'm already developing grey hair by trying to sort this out.
Edit: I've seen some examples where they do that by #anchoring, or with a ?get_variable, but I'd rather do it by changing the URL-proper, like Asana.com does it.
You're looking for JavaScript's pushState() method in the history API:
Manipulating the browser history
Note: you can check compatibility with browsers on Can I use...

Designing Web Album: CSS or Ajax?

I want to design a web album with every image in the album having it's own title, and description. So, at a time only one set of image, title and description would be visible. And on clicking next button, the next set of image, title and description would appear,and so on.
So am wondering, what would be the best way to design with? HTML or AJAX?
I don't want to use the ready to use tools such as lightbox.
Do you want the browser's back button to work? If so, then you should make your life simple
and use html (since you will only be displaying one image at a time either way).
Ajax implies using html. On the other hand, using html does not necessarily imply that you need to use AJAX to load content dynamically.
What is the purpose of this project? If you are doing it for the learning experience you should go on with AJAX (from scratch). If you want speed and quality use an existing web image gallery. If you need to write it yourself use plain html (or an ajax framework such as dojo, jquery, etc. this will save you a lot of pain solving cross-browser quirks).
In addition, if you want to be able to click a button to take you to the next (previous) image
and you don't know how many images you will have beforehand, then you are looking for dynamic behavior. You can code dynamic logic either on the client side (javascript), or on the server side (let's say "php" to start with).
Also, how do you plan to keep the corresponding (image, title, description) together?
If you only have a 3 images, say you could hard code each of this into its corresponding html file. eg. 1.html, 2.html, 3.html. Then you would have to point the forward button from a.html to point to b.html. etc...
If you didn't want this boring static behavior and wanted something smarter, say you decided for AJAX. Then you would only have 1.html file and from there (using javascript) you would ask your server for the (image, title, description) and load all that (dynamically, without refreshing the browser) into the same page. The easiest way to get this from the sever is by just reading a a static (XML, or JSON) file which contains all the info (image urls, titles, descriptions). Then with javascript and using DOM manipulation you would remove the old image, and add the new one.
However, this would all be a lot simpler with server-side processing (and it's worth learning). In this case you could have a url which takes a parameter with the image number. eg. http://example.com/gallery/index.php?image=X
then before the server responds to the client with the html, it would realize that you want to load image X so it would get it's corresponding description, title, and url. and "embed" those into the file. Of course, depending on the number, it would also add the right links for the previous and next buttons. Eg. If the currently displaying image was 9 then forward button would "dynamically" be determined to link to (X+1) : http://example.com/gallery/index.php?image=10

What are the "best practices" for AJAX with Django (or any web framework)

I am developing an issue tracking application in Django, mostly for a learning exercise but also for my own projects - and I am looking into using some AJAX for "enhanced" usability. For example, allowing users to "star" particular issues, which would add them to their watch list. This is implemented in a lot of sites, and is often AJAX - as the URL that the user is viewing doesn't need to change when they click the star.
Now, I am wondering what kind of response to return from my star_unstar view - that detects whether the request is being made via AJAX or not.
At present, if the request is an AJAX request, it returns just the section of HTML that is needed for the star, so I can replace the HTML in the star's parent DIV, so as the star appears "on" or "off", depending on the user's action.
However, I would much rather return some kind of JSON object, as it just seems more "proper", I think. The problem with this method is that the javascript would have to modify the star image's src attribute, the href on it, and the link title also, which seems a lot of work for such a simple feature. I am also looking into in-line commenting in the future, but I want to get a feel for how things "should" be done before I start coding lots of JS.
What is the general consensus when implementing features such as this, not just with Django, but all frameworks that operate in a similar way?
When I work with Ajax my main concern is usually to limit the amount of data I have to send. Ajax applications of this type should be very responsive (invisible if possible).
In the case of toggling a star, I would create the actual on/off states as CSS classes, StarOn and StarOff. The client will download both the off and on star when they first visit the page, which is acceptable considering that the star is a small image. When you want to change the star appearance in the future, you'll only be editing CSS, and won't have to touch the javascript at all.
As for the Ajax, I'd send back and forth one thing -- a JSON variable true/false that says whether or not the request was successful. As soon as the user clicks on the star, I'd change it to the StarOn state and send out the request. 99% of the time Ajax will return true and the user will not even realize that there was some sort of delay in the web request. In the rare case where you get a false back, you'll have to revert the star to StarOff and display an error message to the user.
I don't think your question relates particularly to Django or Python, as you point out at the end.
There's a lot of personal preference in whether you return a blob of HTML to write into the DOM or some serialized data as JSON. There are some practical factors you might want to take into account though.
Advantages of HTML:
- Easy and fast to write straight into the page.
Advantages of JSON:
- Not coupled to the front-end of your application. If you need that functionality anywhere else in the application, it is there ready to go.
My call on it. It's only a relatively trivial amount of HTML to update, and I'd probably go for returning JSON in this case and giving myself the extra flexibility that might be useful down the road.

Reload the page without submitting it back to the server

the problem I have is that I have two sets of values in a drop down list. If type 'A' is selected I want a text box to be populated with a value from the database and be read only. If Type 'B' is selected the box is to be empty and editable.
My original code is written in jsp/struts and I have sort of achieved this by using
onchange="javascript:submit()" to reload the page, but this has the obvious drawback of saving any changes you have made which means you can't really cancel.
I also have other problems with the serverside validation due to this method.
Is there a way of making a jsp page reload on change, that way I could write javascript to change the way the page looks according to the values held in the session. That way the save/submit function will only be called when the page has properly been filled out and the server side validation will work as designed.
I know that this is something that AJAX is good at doing but I am trying to avoid it if possible.
AJAX is your only other option my friend, unless on the original page load you load all the other possible values of the Text Box so you don't need to go back to the database. Well, you could try putting the text box in an IFRAME, but you will probably run into more problems with that approach than just going with AJAX.
Without AJAX what you are asking is going to be difficult. Another option (which is ugly) is to write out all possible values for the second list box into a data structure like an array or dictionary.
Then write some javascript to get the values from the data structure when the user selects from the first list box. The amount of javascript you will have to write to get this done and to do it correctly in a cross browser way will be much more difficult than simply using AJAX.
Not sure why you'd try to avoid AJAX in today's world, the JS libraries out there today make it so simple it's crazy not to try it out.
I just had to replace a page that was written as Vincent pointed out. I assume at the time it made sense for the app, given the relative size of the data 4 years ago. Now that the app has scaled though, the page was taking upwards of 30 seconds to parse the data structures repeatedly (poorly written JS? maybe).
I replaced all the logic with a very simple AJAX call to a servlet that simply returns a JSON response of values for the 2nd drop down based on what was passed to it and the response is basically instant.
Good luck to ya.
One way is to change the form's action so that you submit the form to a different url than the "save" url. This lets you reload certain aspects of the form and return to the form itself, instead of committing the data.
<script>
function reload() {
document.forms[0].action="reloadFormData.jsp";
document.forms[0].submit();
}
</script>
<form action="saveData.jsp" method="post">
<select id="A" name="B" onchange="reload()"><!-- blah --></select>
<select id="B" name="B"><!-- blah B --></select>
<input type="submit">
</form>
If I understand you correctly, that you want either a dropdown (<select>) or a textfield (<input type="text">) depending on a choice (typically a checkbox or radiobuttons) somewhere above in a form?
I that case you may need to handle the two types of input differently on the server anyway, so why not have both the selectbox and textfield in the area of the form with different names and id and one of them hidden (display = none). Then toggle visibility when the choice changes. On the server you pick eiter the selectbox or textarea input (wich will both be present unless you disable (disabled="disabled") them too, wich I think is uneccesary) depending on the choice input.
Of course if you expect that the user usually just need the text-input, and a few times only, needing a massive list; it would be better to use ajax to retrieve the list. But if it's the other way around (you need the text-field only occationally), as I assumed above, it will be faster to have both present in the initial form.
If the drop down only contain easily generateable data, like years from now to houndreds of years back it could even be much faster (requiring less bandwidth on the server) to generate the data client side using a for loop in Javascript.
I know a taglib that can fit to your problem:
AjaxTags.
I use this taglib in my J2EE projects and it is very simple to integrate it into web applications.
This taglib give you several tags designed to execute AJAX request in your jsp files.
Here is the description of each tags: http://ajaxtags.sourceforge.net/usage.html
The tag which will help you is the ajax:select tag. It allows you to populate a select tag which depends on an other field without reloading the entire jsp page.
If you more informations about it, ask me and i'll try to answer quicky.
Along the lines of what Strindhaug said, but if you need dynamic data:
Could you have the backend write JS into the page, and then the JS would change the form as required? The backend could propagate some variables for descriptions and such, and then the JS could change/update the form accordingly. If you aren't familiar with this, libs like jQuery make things like this easier and more cross-browser than rolling-your-own (at least in my experience).
Aside:
If you're not using AJAX because it was hard to code (as I didn't for a while because my first experience was from scratch and wasn't pretty), as others have said, libs like MooTools and such make it really easy now. Also, there is not shame in using AJAX properly. It has a bad rap because people do stupid things with it, but if you can't simply write premade values into the form or you have to do live look ups, this is one of AJAX's proper uses.

Resources