Efficient way to store form data? - php

I have a web app that has a big and complex form (fields, checks, etc).
I hade using standard OS form controls because they have visual (styling) limits.
I have been basically creating spans with IDs and attaching class or custom data attributes. I later need to send this to a PHP script for insertion into a database. This has worked well in the past, but I'm having to do a lot of manual processing of fields, which I don't think is efficient... Is there a better way?
I currently do,
IF ($('#foo').hasClass('on')){bar=1}
...
Then I manually compose a POST string via
foo=bar&bla=blabla ...
Then lots more on the PHP side to create an insert SQL statement.
Seems like its inefficient if you have dozens of fields... But I hate standard FORM elements...
Any suggestions? .... Loops? Arrays?

You should use a form. But how to make it pretty?
With JavaScript you can have a kind of front-end for the form. Hide the form elements and have some JS that changes the form field values on interaction.
Search for pretty forms jquery in Google.

You could use jQuery's serialize() method:
$('form .on').serialize();
jsFiddle example

From what I understand is that you don't want to manually get the value of each element that has the class 'on'. You could use jQuery's each function looping through all the elements you need. Something like:
​var query = "";
$(".on")​​.each(function(i){
if(i === 0) {
query+="?"+$(this).attr('id')+"="+$(this).text();
} else {
query+="&"+$(this).attr('id')+"="+$(this).text();
}
});
(see: http://jsfiddle.net/MkbrV/)
Is this something you are looking for?

Related

Is there a way for server-side php to see HTML attributes?

I want to make a reusable form validation system, similar to something that would be implemented in Javascript. Ideally I could use things like class names or input types from form elements to decide what validation tests to apply.
Is there a way to implement this in PHP? That is: Is there anyway to get a hold of these HTML attributes on the server-side?
Yes, see DOMDocument. But I'm not sure I would recommend it based on what you're trying to do, as that could get pretty ugly.
I had a similar idea and asked on StackExchange a while back.
Try getting the input through $_POST['field_name'] and loop through the array given by wesly murch. Add switch statements like
if arraykey=required // doo something
arraykey=minlength=> //do something

PHP: Populating a drop-down from database; sending result to new query

I already have posted an unanswered question (Dynamically populated drop-down; $_POST returning error ) that deals with the specifics of my case, but it hasn't gained much traction, so I thought I'd go another route.
Would anyone be willing to instruct me on how to perform this simple task:
I have two tables.
I want to populate a drop down menu from the results of a query from one table:
I want to take the $_POST from this drop-down and perform a query on the second table and print those results.
Sounds simple right? I've been pulling my hair out trying find help to make it work. See the link in the first paragraph to see the specifics of my problem, or if that's the wrong route, please instruct me in broad terms how to accomplish this.
What you are trying to get is usually called "Chained selects", you are missing one immportant step, Javascript (or just use jQuery) to make AJAX calls to populate the second select.
Try with a simple tutorial: Chained Select Boxes using PHP / MySQL / AJAX / jQuery http://www.blueicestudios.com/chained-select-boxes-using-php-mysql-ajax/
You can use the onchange="" to trigger a AJAX request to query based on the value.
or with jQuery
$(document).ready(function() {
$(".machine_select").change(function(){
//do ajax and replace response with html() or such
alert($(this).val());
});
});

Submit multiple forms as one

I have two forms on the page. To the user it looks like 1 form, and I actually wish it was one form. But the way I'm trying to reuse code and include things, I can't avoid two forms in the source code... trying to act as one.
I don't want to do ajax submit, I want a normal post submit, my form handler has redirects in it. How can I submit both of these, and get values that make sense on the server side. something like $_POST['form1]['whatever'] $_POST['form2]['thing']
Maybe take all the inputs from form 2, rename all of them with a prefix, and append them to form 1? I can't find a non-messy way of doing this. I don't think I need code, just a plan. Least messy idea wins.
Maybe take all the inputs from form 2, rename all of them with a
prefix, and append them to form 1?
That's exactly what you have to do. Wouldn't be much of an answer without a code sample, so here you go.
$("#form2 :input").appendTo("#form1")[0].submit()
now in php you'll have $_POST['thing'] containing an array with two values. Alternatively you can rename all of the inputs from form2:
$("#form2 :input").attr("name",function(name){
return name + "_form2";
}).appendTo("#form1")[0].submit();
You can try to collect values of one form with jQuery.serializeArray() and then generate hidden inputs with names and values from variable storing result of previously called jQuery.serializeArray() and insert them to second form on submit event of form.
You should be able to combine both forms fields into one single form in PHP. If your code doesn't allow it, it must be in terrible shape.
If you are using simple scripts, you should be able to cut the forms into parts producing the fields, and the other parts producing the form outlines, either as separate scripts, or simply as separate functions.
i.e.:
<?php
function form_body($params) {
// here's the code for echoing fields according to $params
}
function form($params) {
// here's the code to build the form properties
$f_properties = '....';
echo '<form '.$f_properties.'>';
form_body($params);
echo '</form>';
}
?>
Then it's just a matter of combining $params from form1 and form2 to get the definitive form.
If you're using OOP, it's probably very easy to derive a new class containing both forms, and have it output their fields.
This are very simplistic advices, but you don't provide any source to help refactoring, so I can only provide vague/generic code examples.
Going the js way to combine forms on the client side will turn into a lot of problems down the line to maintain and evolve the code, and bring a lot of issues (security not the least of them).

Adding rows to MySQL db and showing DIVs with jQuery without refreshing a page

I am using some PHP script to add some data from a complex form to MySQL db and then showing it all in some HTML table. Everything works just fine, but I would like to 'upgrade' my script with jQuery and (I suppose) AJAX.
What I would like to do is when user submits data, the row (or <div>) shows up in the HTML table without refreshing a page. Form and table are on same page, of course...
Some guidelines would be really helpful because I'm not sure should I even use AJAX or something else for my needs. Links for some tutorials will be also great :)
Thanks a lot for any help!
An easy way to do this is using jQuery POST method
http://api.jquery.com/jQuery.post/
When the user submits the data, you use jQuery to post the data to a PHP handler, which saves the data to the database and returns a HTML formatted row to add to your table.
Here's a good example:
http://www.jensbits.com/2009/10/04/jquery-ajax-and-jquery-post-form-submit-examples-with-php/comment-page-1/
I had used this tutorial to implement a comment system on one of my projects. It uses ajax and works really well. I believe that this is what you need.
You'll need:
A php page where to submit the form. Ideally this page will return the result as a JSON object (PHP has some handy JSON functions to convert PHP arrays and objects directly to a proper JSON string). Don't forget to include some error information in the JSON object you return. This can have the form:
{
"errorCode": 0,
"result":
{
"var1": value1,
"var2": value2
}
}
Some javascript to submit the form. This can be done nicely with jQuery.ajax, jQuery.post or jQuery.get functions.
Some javascript to handle the result from the PHP script. This will be a callback function that you give to the jQuery.ajax, jQuery.post or jQuery.get functions. This script will either:
display the errors to the user (you can set some text in a div for example using jQuery("#error").html("My error message");)
Insert the row in your table. You can build HTML elements dynamically using jQuery.append and jQuery.html functions.

Possible to populate a php/mysql call with a value selected within form on same page?

I have a form which has two inputs. The first input allows a user to select two values (either 1 or 2). My second input allows the user to select a range of available dates (which is populated from a separate php/mysql query).
I would like to achieve the following:
At page load, the second box is simply 'non-clickable'. The user must make a selection in part 1.
Once a user makes a selection in box 1, the values of part 2 are dynamically created accordingly as the value selected from part 1 (either 1 or 2) is used in a php pdo prepared statement into a mysql database.
is this possible?
Yes, it's very achievable using jQuery . When the page is ready, you'd disable the second input, and bind it being enabled to the first one being filled out. Then you'd use the jquery ajax function to get the data for the next one and populate it that way.
You should probably read a basic jQuery tutorial, then read the documentation for the specific functions like ajax().
Trust me, you'll be really glad to know jQuery as it comes in handy for all types of things, especially situations like these where you need to setup somewhat complex dynamic forms with ajax calls to your server along the way.
Yes you want to use ajax. I would advice you to take a look at jquery.
Jquery would help you to work around doing the ajax calls and manipulating elements in your page.
Your example should fairly simple to implement using the library.
window.onload = function() {
var input1 = document.getElementById('input1'),
input2 = document.getElementById('input2');
input2.disabled = true;
input1.onchange = function() {
input2.disabled = false;
// Build whatever you want here
input2.value = 'whatever';
}
}

Categories