is it ok to simply point all forms action to a single url and seprate them with a input_hidden for example form_id?
for example we create a url like: /process
and point all forms on that url , and there we seprate forms by a hidden counter
Actually there is no harm in doing that, but if you make different files than it will make a lot easier for anyone to understand.Making different files and calling them will make your code look cleaner.
No, it's not wise. Separate unrelated functionality to different files, and call those, it makes it easier to see where is what. Lots of small files > One huge file.
A few is typically OK, but only if you have lots of different forms on the same page and you aren't using Ajax to submit them. The way you keep it tidy is by giving the forms names, and namespacing each field with that name so you know which form has been submitted.
This is often necessary in this case to reduce the work needed to load form validation errors, whereas you would normally need to keep the errors in the session to reload after a redirect from the processing page.
Example:
-> contact.php
-> Submit to contact.php
-> If errors, re-render the form without redirect on contact.php
-> Else, process the form, then redirect.
In the event of errors, the second showing of the form would be part of the POST request, meaning you still have easy access to the previously submitted data.
If it was valid, you no longer need the posted data as you have already persisted it elsewhere.
This is highly contextual however. It is not a reason to use a single script to process "all" of your forms. Only the ones on the active page.
Generally no.
But there are use cases where it's desirable to do it, at least for some forms. But these forms must implement the same interface, their behaviour is the same.
For example I have one use case where buttons are placed on page, each loads a different form in a modal. Each is posted to the same controller, but all the controller needs to know is that it calls validate(), save(), and render() methods on the form.
I'm sure there are other cases, but your general stand should be "no", unles you have a good reason for it.
Related
I've just started learning PHP and just done with $_POST/$_GET.
Now I want to know, what is the pro's and con's of having the PHP to process the data from a form inside the same file, or send the data to another file (action="anotherfile")?
Logically I will think that sending it to another file would increase the time process it, but is that true?
When I have the PHP script inside the same file, the page doesnt seem to reload when I hit the submit button (but the content changes). Or does it? If it does, wouldn't the only difference would be that I would have to type the script for the menu (lets say you have the same menu on all pages) in both files? Which would lead to more coding/less space?
what is the pro's and con's of having the PHP to process the data from a form inside the same file, or send the data to another file (action="anotherfile")?
You are conflating files and urls.
By having the logic split between different files (and then included where appropriate) you seperate concerns and make your code easier to manage.
By having a single URL be responsible for both displaying the form and processing the form data you don't end up in the awkward situation where the result of processing the form data requires that you redisplay the form with error messages in it. If you used two different URLs there you would need to either display the form on the processing URL (so you have two different URLs which display the form) or perform an HTTP redirect back to the original URL while somehow passing details of the errors to it.
Logically I will think that sending it to another file would increase the time process it, but is that true?
No. It makes no difference on the time scales being dealt with.
When I have the PHP script inside the same file, the page doesnt seem to reload when I hit the submit button (but the content changes).
It does reload.
If it does, wouldn't the only difference would be that I would have to type the script for the menu (lets say you have the same menu on all pages) in both files?
That's what includes are for.
In any language we always try to write clean code. That's why we follow MVC.
Logically I will think that sending it to another file would increase the time process it, but is that true? I think NO.
Because when we send data to another page and on another page at the top we echo that post data and exit. you will see it will not take time. it take time when we redirect/load some html page after that.
It does not matter where we sending data (same page or another page). matter is what is loading after that.
There is no difference about speed.
Whetever you post the content of your form in standard submit, this data will be sent to the server and a response (after processing ) will be downloaded.
The only difference is about organization of your code. The logic that draws themplate of page (menu or other fixed parts) should be stored in some file that you can include separately or call by a function.
Is also true that when you post your data you do for some reason, register a user for example. Is a good pratice that the php file that handles user registration will do that and output the messages and not other functions.
If your file has some logic switches that make it output either an empty form or a a registration message based on the presence of post or get variables, you will notice that when you scale to more complex tasks this will add complexity and make code mantainment harder.
I'll try to make sure I understand your question by restating it.
If you have a form (/form.php), and the "action" of that submit button leads you to a separate php page (/form_action.php), there is absolutely no difference in speed. Each HTTP request (form.php and form_action.php) is independent - "form_action.php" doesn't remember anything about "form.php" unless you pass that information through (as parameters). This is what people mean when they say that HTTP is stateless. It's worth learning about how HTTP works in general alongside the details of PHP.
If you have a PHP script which in turn includes other PHP scripts, there is a tiny performance impact - too small to measure in pretty much any case I've ever come across.
However, using includes allows you to separate your markup (the HTML) from the logic (the PHP). This is a really good thing if you are doing anything other than tinkering. It allows you to re-use functionality, it makes it much easier to change and maintain the code over time, and it helps you think through what you're trying to achieve.
There are many different ways people have solved the "how do I keep my code clean" puzzle; the current orthodoxy is "Model-View-Controller" (as #monty says). There are also PHP frameworks which make this a little easier to implement - once you've got the basics of the language, you might want to look at Zend or TinyMVC (there are several others, each with their benefits and drawbacks).
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. ;)``
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.