Adding multiples of an item to a form, without javascript? - php

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.

Related

Remember checkboxes in Smarty engine

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.

Re-insertion of user inputted values. php or .post

This question might sound a little amatuer but just curious to find out.
So i've got a form field that consists of mixed text-boxes, selectboxes and textareas. It stores its user-inputted values in the database and have the values re-inserted everytime user wants to re-edit the form.
My question is for the re-insertion process of the form fields via stored values in my database, is it better to use 1) php mysql queries or 2) doing a .post that calls another script, json-encode the data and using jquery to insert the values into the form on .ready?
I would appreciate if someone would be able advise me the better way to do it and explain the complications of each method. Like say, which method would you choose and why would you choose it?
Would it incur more bandwidth? disk space on my host computer?
Any help would be greatly appreciated.
Either way is valid, but I personally would go with the PHP approach. The reason for this is if you do it via AJAX then you're form will load and a second later your fields will populate. That doesn't feel very professional and damages the customer experience. Whereas with PHP prebuilding the data, the form is already built and ready to go =)
As far as optimization, it's going to be un-noticable on the PHP side. But they will certainly notice un-populated fields suddenly being populated.

how do you cache information using ajax, php, or jquery?

I'm trying to understand the use of caching data. i know a little bit about it. It helps data load faster because its stores the information in the browser?
If someone can help me understand this better, i'll be grateful. Also, is it possible to cache values from an input field and retrieve it or store it for later use? If so, can someone show me a sample of how it can be implemented in PHP, ajax, or jquery or guide me to a tutorial?
Thanks!
This season's fashion is to use localStorage for storing data on client's machine.
See for example this: http://php-html.net/tutorials/html5-local-storage-guide/
A cache is something which sits between a data source (database, hard drive, web resource, etc) and something that needs to access that data source. The idea is that accessing the data from the cache should be faster than accessing the data directly off the data source.
If you want to store text field values for use later, (without knowing more about the specifics of your setup), I think you're looking for a cookie.
When the user types text into the textbox, use javascript to set a cookie.
The next time the user visits the page, you can retrieve the things they have typed into the text boxes by using javascript to see if the cookie exists and if so, what's in them.
Note that this method will cache the data on the user's computer - not on your web server. If you want to store these values on the web server then you will need to write them to a file or database when the user submits the form, or use AJAX to send the value of the input form to your PHP back-end asynchronously, so it can store the value there.
If you can be a little more specific as to what you want to cache/store and why you think you should be doing it, then we can give you a better quality answer with some code examples.
Please describe exactly what your problem is, and what you expect the solution to do.
Edit: From your previous question it seems like you want some sort of auto-complete functionality. There are two-types:
1) Auto-complete what the user has previously typed:
When the user submits the form, you can do one of 3 things:
a) Store the text input in a database. When the user next visits the page, use PHP to embed the previous searches in the javascript (probably as an array). As the user types in the text-box, use javascript to display the auto-complete box. (Faster for the user, not so practical if you are expecting to store a huge amount of previous inputs per user)
b) Store the text input in a database. When the user visits the page, use AJAX to retreive the most likely match as they type. (Slower for the user, but better if you're expecting lots of saved searches per user)
c) Store the text input in a cookie. When the user submits the form, save the input in a cookie. You can either store multiple searches in multiple cookies, or 1 search in 1 delimited cookie. Note that the maximum size for a cookie (including it's name and other details is 4K, so you should keep it's body under 4000 bytes).
NOTE: If configured that way, the browser should automatically auto-complete what the user has previously typed. The only reason you would want to implement this type of auto-complete yourself is if you want some sort of cross-browser or cross-system functionality.
2) Predictive auto-complete like when doing a Google search.
This method essentially works the same as 1b. You will have stored in your database a list of previous or suggested search terms. As the user types text into the input field your AJAX request will fetch the most likely candidate for what the user is searching for.
It depends. You can cache images, css, js almost everytime because it is always the same. You do not need to do anything, they should cache automatically.
You can also cache GET and POST responses, but that's a bit responsible. You have to know what, when and how often should you flush it.
To turn on cache on GET requests by jQuery alone, use
$.ajax({
'cache':true,
'url' :'ajax.php',
//and more parameters
});

How to _Post combination of formdata and non-formdata to php

I have a form I am creating and I would like to send information, not just from the form itself (easy enough to do with $_POST), but also generated information that corresponds to form data but is not visible to the user.
I could create a hidden input to put the data in, but I wonder if there's a way to do it that doesn't seem so hackish :)
(it's to submit a number of items, some new and some edited, I have a variable that increments for the edited ones but not the existing ones, and I need to be able to separate them out on the other end)
You're trying to maintain state across HTTP requests...
In any case you'll have to create a temporary variable server side. Something in the $_SESSION variable. There's not safer place to put data, primarily because only the developer can access this variable.
The disadvantage of this approach is the developer will have to start maintaining sessions.
I see nothing particularly hackish in using hidden fields. If your concern is about security (you don't want that the end user is able to tamper with the data) you'll have to use some sort of persistent server-side storage such as a database or a PHP session. Whatever approach you choose, make sure your app doesn't break when the user opens several tabs.

What's the best way of displaying fields on screen after a user posts a form, without going back to the db?

I have 3 arrays of data that are used to populate some fields on screen. When a user posts the form (unrelated to the data contained in the arrays) I want to display the array data on screen again, but without retrieving it from the database when the page reloads. What's the best way to temporarily store these values?
I was thinking of storing them in the session, is that bad practice? Is there a better way, perhaps passing them as hidden form values?
Another option could be to serialize the array and save it into a temporary file.
About the question session vs. hidden form fields: The disadvantage of the form fields is that hackers could see it in the HTML source code and misuse it. So you would have to do some extra checks to see if the form fields are in any way valid or not.
The problem with session and serialize is, that the information would be laying around on the server if the user is moving away from the website before he finished the whole process.
And the last thing: You are not writing how large those arrays are. If each of those 3 arrays have several thousand entries then serialize could be a better option than the session and form fields.
Probably sessions is what you need. But the other things should be taken into account too.
Generate a set of hidden inputs in the form. Then you can just read them from the post.
Sounds like a perfect use of session. I'd just caution to make sure that you have proper error handling in the database function, because you definitely don't want to mislead a user into thinking the data was saved, when there was actually an error.

Categories