How can I remember checkboxes in Smarty when I create them dynamically?
If a user fills in a webform and he submits the page and there are errors they are always gone. (The ones that are checked)
I should have a way to store them.
Currently I set them the following way (in a {foreach}:
{html_checkboxes values=$event#key output=$event#key selected=$event id=$event#value name=$event checked="1"}
Thanks a lot for helping me out.
That question isn't Smarty-specific in my eyes. It can be done in more than one way. Two examples to demonstrate how to cope with this:
Use a JScript libraries form validator to validate the data before submitting. An example if you're using JQuery can be found here: http://jqueryvalidation.org/ (there are many more out there for nearly every JScript library, I just chose JQuery as an example because its current widely acceptance).
Don't transfer the form data to your server using the form submit, use some AJAX to submit them and wait for a response from your server. If the response is "oops, error", show the user the field which contains the error.
Again, there's more than those ways of doing it, but - depending on what the form does - those two are usually the fastest and easiest to implement.
Related
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. ;)``
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.
Apologies I can't post any code at this time cos I'm away from my desk, but I will try and explain my problem as clearly as possible in the hope someone can help!
I have a long form that submits to a method in a controller. To make things more user friendly I have split the form into sections. Each section has a hidden field that acts as a flag. The method that the form submits to is made up of conditionals that test for these flags. If a flag is found then the next part of the form can be displayed. I can also gather the data in sections rather than processing the whole lot in one go.
My problem arises when I try to use the set_select method to set a default value for select menus. The method is part of the CI system form_validation library. If an optional third parameter is passed to the method as true it should set that value as the default. However, this only works if the form_validation hasn't previously been run. This makes perfect sense because it is assumed that a default would only be needed the first time a form is seen ie. before any submission and therefore before any post data.
Ofcourse this isn't how it is in my situation. If i simply empty the post array then that defeats the point of the set_select function because any select menus higher up the form would no longer be able to be set to their last value.
Can anyone think of a good solution? I know this would be much easier with AJAX, but I want to make sure that everyone gets the best possible experience whether or not they decide to use JavaScript.
Personally, I would use AJAX to break the form up into your 3 sections, submitting by AJAX each time.
THEN for non-javascript users (the few there are), I would just display the form in its entirety, and process normally.
breaking the form up sounds like a "feature" not a function. Meaning that javascript users will be able to take advantage of the "feature" of breaking the form up, while non-javascript users will still be able to effortlessly accomplish the "function" of submitting the information.
what about doing it like this:
split it into 3 different form in 3 different method
on each method, set switch using session to check what form currently is
add form validation on each of these form and check accordingly
if those 3 form is OK then you can proceed to whatever process you want
if some form is failed, you load back the previously failed form
I've decided that using set_select is probably not the best option for me, so I've added some code into my view files which will do this for each individual case rather than trying to use a generic function.
Not ideal, but is working!
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.
I'm building an application which uses ajax calls for form validations and some others, problem is that I don't like it when those validation errors shows up on a new page with no css at all and form completely gets reset without the javascripts.
I'm talking about a dozen forms so, it will be quite annoying for the user to go through forms over and over again.
I've read some answers on this topic, but is there a specific way, a best-practice for a situation like this (more along the lines of form validation)?
Apologies if there is an answer already.
Edit:
All validations are done on the server-side, currently the errors are being displayed with the help of ajax. What I'd like is a convenient method for repopulating the form and display errors without javascript if an error occurs while processing the form.
I'm not sure if you're implying by your question that you don't validate on the server - this would be considered a huge security hole as quite obviously forms could be bypassed by simply disabling Javascript. You have to validate in the server every time, while client-side validation is simply nice to do.
Furthermore, the "problem" of having the forms reset themselves when the page is reloaded becomes moot when you use a decent framework - In Python, Django auto-repopulates forms in the case of errors. In PHP, CakePHP and CodeIgniter do as well, and I'm sure most good frameworks do this, as it falls under the category of "common tasks" that frameworks are supposed to abstract away.
Whenever I'm not using a framework, I write up my own little Form class that fills the need.
EDIT:
I am not aware of anything you could plug-in to what you have to be able to repopulate the form. Your best bet is writing your own little class for it, which should take no more than 1 hour.
What I normally do is store all the error strings in an array in a session variable (I use PHP). If there's an error on the server-side, redirect the user back to the form page, check for the session var, and display the errors as appropriate. Make sure you unset the session var to free up memory after you display it. Same goes for repopulating the form -- values in a session var.
Form validation should be written on the server first, on the client later. You should be validating on the server in any case. Don't rely on Ajax for something as simple and as crucial to the operation of your site as form validation. Using unobtrusive scripting, you can prevent the default form submittal and then process the form using Ajax. Otherwise, allow the submit to go through and respond with a server-generated validation page.
Perform your validations on the server-side and repopulate the forms.
Validation via AJAX is nice, but cannot be enforced. Thus, it is more effective to make the validations be performed whether or not the AJAX happens. I would suggest a second route that can handle the validations and pass back an array of errors in JSON for those who have javascript. But for those without javascript, the only way your validations will work is through the server-side.
You don't really get a choice in this, unfortunately. Any halfway decent programmer or hacker with firebug can edit your javascript, detach hooks, and get around everything you're trying to do on his side: be paranoid and enforce validation on the server side.