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.
Related
This question is a little n00b-ish, but I haven't been able to find a satisfactory solution in the CakePHP docs or via google.
I'm trying to make a simple AJAX form that will update some information in a database, and also display that information on the page. The whole process seems straightforward enough, except I can't figure out how to pre-populate the update div.
In my view code, I have
<div id="interestingContent"></div>
<?
echo $this->Form->create();
// create form fields here
echo $this->Js->submit('Save', array('update'=>'#interestingContent');
echo $this->Form-end();
echo $this->Js->writeBuffer();
?>
This works great, and when the form is submitted, my controller correctly calls
$this->render('ajaxview','ajax')
and updates the #interestingContent div appropriately.
So, the question: What's the best way to pre-populate #interestingContent from the database? Of course I could just repeat the code from ajaxview.ctp inside #interestingContent, but it seems there must be a DRY way to do it.
My first thought was to make ajaxview.ctp an element, since I'm basically trying to embed one view inside another. That seems hackish to me, though, since my controller would then be rendering an element's view directly. I also considered the new view blocks in 2.1/2.2 but that doesn't seem right either.
I'm certain this sort of thing comes up all the time. Is there a generally accepted method of doing this?
I had the same problem. It may be hackish, but using an element wil do the job.
First, create an element for representing your bd content.
In your form view, you use the element.
And you create another view that will contain only the element. This view will be the response to your ajax request. By using an element, you prevent code duplication.
I am writing a cms (on .net) and have structured the whole page to work client side.
There is a treeview that lets you add/remove/move items and define their names in the languages defined. For each language I save the names of the category defined, but when there is HTML content associated with it, i fall into the JavaScript serializer problem that finds the content too long to be serialized.
What would be the best approach to make sth like this work. Shall I change everything to work with postbacks, or try to manually call _doPostBack for the editor content (which I don't want). Thank you in advance.
I guess would be great to make auto-save with time interval which will submit only diffs between current state and previous save. It will do the key if the user will edit it manually, not for copy/paste, of course. It is if we talk about really big data that we need to save.
Otherwise need to find some ways to compress the data before submitting: json+base64, etc.
It seems that the sites and applications that use AJAX are growing rapidly. And probably one of the major reasons for using AJAX is to enhance the user experience. My concern is that just because the project CAN use AJAX, doesn't mean that it SHOULD.
It could be that AJAX is exposing more security threats to the site/app for the sake of UX. Maybe you have other reasons for not using AJAX.
When should the use of AJAX be avoided?
Getting Data Already Available Or Data Easily Obtainable
I usually see that on car websites, where there are makes and models. Their usual <select> (without JavaScript) include <optgroup>'s as such:
<select>
<optgroup label="Ford">
<option value="21">Escape</option>
<option value="21">F-150</option>
</optgroup>
<optgroup label="Toyota">
<option value="51">Corolla</option>
<option value="52">Yaris</option>
</optgroup>
</select>
Then usually then proceed to hide that <select> and create 2 new select, one for makes and one for models.
All is fine up to that point. They start messing up here.
They then process to query the server to get a list of makes, and then do another query to get the list of models, when they could of simply parsed the original element try to get their information. Then, everytime you change make, another request is made...
The above is a excellent example of when NOT to use AJAX. Consider this: a request is longer than parsing available data, so they make the user wait. They probably query their database each time, so it has a hit on their server CPU usage. And it incurs more bandwidth. Terrible waste of resources.
What they should have done
They should of have simply parsed the DOM try under the <select> to fetch the relevant information. Each <optgroup> is an item in the makes <select> while each child <option> from the <optgroup> is an item in the models <select>.
Other examples
Using AJAX for simple static DOM modifications (you don't need AJAX to switch from one tab to another in most cases, just include the data in your original request).
Using AJAX to retrieve data on load (why not include it with the original request?)
Using AJAX for an image gallery (why not include the images and manipulate them after the request is done?)
You definitely should avoid AJAX when you are sure that your clients will be using "not javascript enabled" browsers
Actually, AJAX should be used to enhance user interaction. If not it, then Flash or what have you.
Naturally, if there's no possible enhancement, there's no reason to go that way. I tag that as highly unlikely. If you find such a case, blog about it: it'll probably make interesting read.
There are situations, of course, where AJAX is contra-indicated. Basically, when you don't have people using the site. If you expect the site to work with SOFTWARE driving the requests, then you must make sure it works fine without AJAX.
And if you don't expect software to drive the requests, I sure hope you have an alternate API for it, one that can do everything the site can. Otherwise you are just deluding yourself and failing your clients.
If your development time is limited or your team lacks sufficient expertise, then you could make a good case for staying away from AJAX programming.
But otherwise:
[AJAX calls are] no more-or-less safe
than a normal HTTP POST request issued
by a browser as in from a -form-.
The "fix" for this is the same "fix"
for non-AJAX requests - use SSL.
I hear this a lot - just because you can make it pretty with Ajax doesn't mean you should.
I don't think you should necessarily put the UI on the backburner though. It shouldn't be the last thing you think about, particularly in certain cases.
The UI is what the user sees - they don't see any of the complexity behind it, so they'll judge the quality of your site/application based on how easy it is to use and how it makes sense to them.
With that in mind, decide on Ajax based on the user's point of view. Does it make sense that when I click on this button the page slides to the left to reveal a new section? Would it comfort me or confuse me to see the page grayed out and a "Working..." image displayed in front?
When redirecting a user to a new page which the user might want to bookmark - i.e. if clicking on a link causes the content to be updated using AJAX, the user can't bookmark the page.
AJAX should be avoided when the same functionality can be implemented entirely client-side without an additional round-trip to the server.
For example, it may be more efficient to seed the client with a list of zip codes for all US States and scope zip code selection to the appropriate set rather than going to the server for a list of valid zip codes for the given state.
It could be that AJAX is exposing more security threats to the site/app for the sake of UX. Maybe you have other reasons for not using AJAX.
How? What security threats?
I am new to ajax and i wanted to know if we can load a complete new page and not just a part of it using ajax. Please give a small example script for understanding if this is possible. Here i am trying to display only one url to user while i change from one page to another when he clicks on any of the links in the page.
You can of course request for a new page and load it via body.innerHTML = ajax.responseText;
I would strongly recommend against this though for reasons outlined in this post: Why not just using ajax for Page Requests to load the page content?
The whole premise really is that with
AJAX you don't need to reload the
whole page to update a small
percentage of that webpage. This saves
bandwidth and is usually much quicker
than reloading the whole page.
But if you are using AJAX to load the
whole page this is in fact
counterproductive. You have to write
customised routines to deal with the
callback of the AJAX data. Its a whole
lot of extra work for little to no
increase in performance.
General rule for where to use AJAX: If
your updating >50% of your page, just
reload, else use AJAX.
You will not only need to request for the new page, but then also take care of ensuring the old styles on the current page are removed and don't interfere with the new page. Theres all sorts of problems associated with what your trying to do. It's possible, but I recommend not to do it.
edit: actually you might be able to just do document.write(ajax.responseText) which should take care of overwriting everything in the document, including css styles etc. Though still don't recommend it.
When you're finished with processing the AJAX request simply use this JS line:
window.location.replace('<URL of the new page>');
This has exactly the effect of loading the new page via
....
When you make an AJAX request, a request goes off and brings you the contents of the URL that you have requested. Now technically you can do whatever you like with the contents (which could be HTML), you can replace any element within the DOM with it. Be careful however of replacing EVERYTHING on the page, you are more likely just going to want to replace what is within the tags.
If what you want to do is show one URL for multiple pages, AJAX is overkill. Why not just use an IFRAME?
This could be useful if your page was unsure if it was expecting back errors to be inserted onto the page or a "new" submission confirmation page. This can be used when you want to put a validation servlet (or whatever) in front of the submission servlet (or whatever). If the page always hits the validation servlet, you hide the submission servlet which actually performs the data update. In the case where the validation passes, forward to the submission servlet. The user never knows what happened in the background.
When the page gets a response back you could just look at the first portion of the response text and determine if it had a keyword set by the server, which means this is a new page. Remove the keyword from the text, and do document.write(ajax.responseText); as described previously. Otherwise insert the response text into your errorBox div and let the user retry submission.
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.