Combine multiple forms $_GET values into query string - php

So, i have 2 forms to filter products, one with checkboxes and the other with select options.
When i check one checkbox the form is submited and the query string is updated with it's value, when i check another checkbox the same happens, but when i select a option, the current query string resets and add only that option value instead of adding it after or before the current query.
What i want is to unite both $_GET indexes in the query string, independent of the order of submit. How can i do this? I'll be grateful if someone knows.
$marca_get = isset($_GET['marca']) && is_array($_GET['marca'])
? $_GET['marca'] : [];
if ( isset($_GET['ordem']) ) {
if ( $_GET['ordem'] == 'vendas' ) {
$orderby = 'vendas';
}
if ( $_GET['ordem'] == 'avaliacoes' ) {
$orderby = 'avaliacoes';
}
}
<form method="get">
<input type="checkbox" id="amd" class="checkbox-filtro" name="marca[]"
value="amd">
<label for="amd">AMD</label>
<input type="checkbox" id="intel" class="checkbox-filtro" name="marca[]"
value="intel">
<label for="intel">Intel</label>
</form>
<form method="get">
<select id="ordem" name="ordem">
<option value="vendas">Mais vendidos</option>
<option value="avaliacoes">Melhor avaliados</option>
</select>
</form>
$('#ordem, .checkbox-filtro').on('change', function() {
this.form.submit();
});

Quotes from Mozilla Developer Network:
The HTML <form> element represents a document section that
contains interactive controls for submitting information to a web
server.
When a form uses the get method, the fields are put into the URL Query String:
get: Corresponds to the HTTP GET method; form data are appended to the action attribute URI with a '?' as separator, and the resulting URI is sent to the server.
Your page has two forms, which is OK if they are unrelated. For example a page with a search form in the header, and a comment form at the bottom, would have separate forms because they do different things. The search form is also likely to have a different action URL than the comment form.
Option 1
The easiest way to get two forms to share state, is to just use one form instead of two.
If you want two forms to be united, and they also share the same action URL, this indicates that they are basically the same form.
The form element groups the fields that belong to a particular action.
The default style of a form element means users cannot see the form's boundary, and a form element can contain other 'non-form' content, just like a form on paper would.
Option 2
Copy the other form's fields, but make them hidden.
<input type="hidden" name="ordem" value="<?php echo $_GET['ordem']; ?>">
Suppose your visual design has exposed a form's boundary (CSS border or background). It may not be visually desirable to contain a significant amount of content.
This is slightly more maintenance. It may be worth redesigning the HTML/CSS so the form element is not styled directly.

Related

How to get the right forms value from a button click

Overview of what my question is:
I have an array that is populated via XML inputs, and from this I am the using it to populate a web form with form controls. From here I want to be able to select the exact form that is clicked, but to do that I need to give the controls some form of unique identifier, which is an issue...
As the site is of a betting nature and I am currently working with horse racing, each horse is given a unique identifier by default, I have tried to add this identifier to the forms.
e.g:
<?php
//Values from feed examples: 123, 234, 345
$valuesFromFeed = array(123, 234, 345); //These are not in my code, they are values from the XML feed
while ($uniqueIdentifier = $valueFromFeed) {
<form name="horse_<?php echo $uniqueIdentifier; ?>_frm" action="#">
<input type="hidden" name="horse_<?php echo $uniqueIdentifier; ?>" />
<input type="button" value="Place bet" />
</form>
}
?>
But then the problem comes when I try to reference this name of "horse_123", I need to know exactly what the value of that name is, which is impossible as there are millions of horses, tracks and races.
Example of trying to get post:
<?php
if (isset($_POST['horse_' . $uniqueIdetifier])) {
echo "You got the right thing here.";
} else {
echo "Still no joy.";
}
?>
The issue with the code above, is that once the $uniqueIdentifier has been used in the while above, it is removed and is no longer usable in this scope.
So to conclude, my point and question:
How do I get the correct name from the form in a submit for the specific horse that I wish to reference and get information on?
How do I use this information as I need to?
Better Description:
I have been given an XML feed and site as part of a handover, this feed contains many hundreds of races and horses.
When this information is loaded into the page, it is also stored in a database on the server, as well as sending it through some different loops (which are messy, but someone else's code I'm trying to clean up!) which split it down and then make up a dynamic menu containing all the races, horses, odds and information. (All information on a single horse within a race is kept in one form)
Next to the information stated in the prior paragraph, is 2 buttons, one that allows the user to take odds and another that allows users to take starting price.
On either of these button clicks, I need the information attached to said horse, and then populate a betting slip. In the form (mentioned above) the name is "horse_<?php echo $uniqueIdentifier; ?>_frm".
The problem that occurs to me is, yes data is stored on the server when it is loaded, that I cannot seem to get the right form via the unique identifier that is put into the form name
Edits
Added form surrounding my input as this is there, I just missed it in original question
Added the button that transmits data to where I need it
Added a better description of my problem
You can use multiple forms, one for each horse. Each form has a different action, where the URL includes the id of the horse. For example:
<form action="/horses/my_unique_horse_name">
...
</form>
<form action="/horses/another_horse_name">
...
</form>
Or you could have multiple forms all with the same action, with a hidden field for the name of the horse:
<form action="/horses/">
<input type="hidden" value="my_unique_horse_name">
</form>
<form action="/horses/">
<input type="hidden" value="another_horse_name">
</form>
Alternatively, you could have a button for each horse:
<form method="/horses/">
<button type="submit" value="my_unique_horse_name">My Horse</button>
<button type="submit" value="another_horse_name">Another Horse</button>
</form>
Beyond that, I don't entirely understand the problem. What kind of data are you submitting and retrieving?

Appending and substracting divs filled with data from one simple form to a form that contains all the divs grouped and ready to POST

So this is the deal:
I have an order page and I use two forms.
The first form contains input data for ONE order item and when I press OK I will pass the form's input data to javascript through onsubmit=send_item_data(this) and at the end i will return false; in send_item_data function so it doesn't get posted.
In the second one I want to append/substract the former data in div groups (so I can add more or delete them easily) but I can't think (or find) of a solution that puts in group the data from the first form in one div and appends that child div to the second form.
In the end, by the push of a button, the second form will post all the divs' data and I will handle it with PHP backend code.
Code body:
<form action="" id="first_form" method="post" onsubmit="return send_item_data(this)">
<div id="Select_list">
<select blah blah>
---bunch of options---
</select>
</div>
<div id="extras">
---Some extras that you can choose by a checkbox input (I generate it via PHP)---
example:
<input name="checkbox[<?php echo $row['column_data_from_query']?>]" type="checkbox" value="checked">
</div>
--->Possibly two more input fields here<---
<input type="button" value="clear" onclick="clear_form()">
<input type="submit" value="OK">
</form>
<form action="" id="finalize_order_form" method="post">
--->This is the second form<---
--->In here I want to put the data from the first form so i can handle them by group<---
if I click OK three times in the first form there should be three groups here that contain each form's data
<input type="submit" class="button" value="Finallize order"/>
</form>
I mainly use PHP Mysql and Javascript (including AJAX, not jQuery).
So you want to have the order items listed in the second form like a pre-checkout shopping cart. If you use divs for that, they will not be submitted with the POST data to the server - they will be display-only. So you need to follow Robert's advice and save the 1st form's data to the DB each time an item is added/removed (in addition to his other reasons like not losing a customer's session info). That way the DB will already be up-to-date when they click Confirm Order. Or else you need to hook the Confirm Order button to a JS function that converts the divs back to JSON and posts that to the server to be stored in the DB.
As far as creating the display-only div from the 1st form's data, your send_item_data function needs to loop over all the form's inputs, get their values, and add them to the div however you want them to be displayed. Then you can just insert the div into the second form. Since you are passing "this" to the function, which is the form object itself, you can get the inputs via something like:
var inputs = this.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type == 'submit') continue; //ignore the Submit button
var name = inputs[i].name, value = inputs[i].value;
---use the name and value of this input to construct a span or something to insert inside your div---
}
---now you can insert the div into the 2nd form---

Process only edited fields in Codeigniter form

I have a multi field search form I'm creating. There are 9 different search fields. None of them are mandatory, though. The only requirement is that you have to fill in at least one field.
They all show a default value (i.e. 'State') upon load instead of using labels to indicate what the purpose of the search field is. So, if you edit one field but leave the other eight alone then all nine will still have a value posted.
Is there any good, efficient way to handle this? I'd prefer to not have to manually do the logic in either jQuery before posting (e.g.if($(inputid).val() == 'Default Value') { ...) or the controller (e.g. if($this->input->post('name') == 'default value') { $data['name'] = '') because there will be a few iterations of this search throughout the site, so a dynamic solution would be incredibly helpful and save a bunch of time.
Thanks!
EDIT
here's the gist of what I ended up with after #veddermatic's post below:
rendered form:
<form id="search-form" action="spend/search">
<input id='fname' value='First Name' data-original_value='First Name' name='fname'/>
<input id='lname' value='Last Name' data-original_value='Last Name' name='lname'/>
...
</form>
ghost form:
<form id="ghost-form" action="spend/search">
<!--nothing here yet-->
</form>
jquery to handle it all:
$('.do-the-search').click(function(e) {
e.preventDefault();
$('#search-form input').each(function() {
var $this = $(this);
if($this.attr('data-original_value') != $this.val())
{
var clone = $this.clone();
$("#ghost-form").append(clone);
}
});
$("#ghost-form").submit();
});
One option would to have two forms, the "normal" form you have currently, and a "ghost" form (it has no submit button or visible fields) with the same target and action as the one presented to the user.
When you build / render the form to the user, give each input a class you can use to iterate over them with, and put the pre-filled value into a data attribute:
<input type="text" class="myFormInput" name="in1" data-original_value="blah" value="blah" />
<input type="text" class="myFormInput" name="in2" data-original_value="something" value="something" />
....
Then handle the user-facing form submit with javascript, iterate over the .myFormInput elements, and if they have a value different from the original value, create an input element with the same name in your "ghost" form, then submit that form. This will only send changed elements, and if for some reason they have javascript off / disabled, your gracefully degrade because your original form will still submit.
EDIT: you could very easily turn this into a plugin and use it on all your forms if you do have multiple instances so you'd just have to do something like: jQuery('#userFacingForm').ghostForm();

Checkbox group add to database

I have the following query that retrieves client data to create a checkbox group. I need to add the selected checkboxes to a database as individual rows, but I am not sure how to write this as I have not done it before. I'm confused because the number of checkboxes will vary in number.
res=mysql_query('SELECT id,name FROM tbl_client WHERE active="1" ORDER BY name DESC',$dbh) or die(mysql_error());
num=mysql_num_rows($res);
for($run=0; $run<$num; $run++)
{
val=mysql_fetch_row($res);
echo '<label><input type="checkbox" name="CheckboxGroup1" value="'.$val[0].'" id="CheckboxGroup1_0" />'.$val[1].'</label><br />';
}
How do I access the checkboxes in order to add them to individual rows in a database when I submit them? I guess I could use some kind of Foreach statement, I just have no idea how to do it.
What you need is to use an array, which means naming your input fields with trailing opening [ and closing square brackets ] like so...
<label><input type="checkbox" name="CheckboxGroup[]" /></label><br />
What this does is create an array named CheckboxGroup in your $_POST or $_GET super globals (depending on which method the form uses), when the form is submitted to your PHP script. So if you had 1 or 1000 of these input elements in your HTML they will all populate under $_POST['CheckboxGroup'] -- or $_GET -- in PHP and you can iterate over them like this...
foreach ($_POST['CheckboxGroup'] as $checkbox) {
/* do whatever you want with $checkbox here */
}
Please note that a checkbox value is only sent in the request by the UA if it is checked. Also please don't use mysql_* functions to interface with your mysql database in PHP as it is deprecated and will be removed from future versions of PHP. For new applications please consider using either MySQLi or PDO to interface with your mysql database in PHP.
In HTML forms, the checkbox and radio controls are unique in that they are not present in the request if they are not fired by the client. So your script has to know in advance what checkboxes to expect. With inputs of type=text, submit, etc., the request contains the named control, even if the data string is empty.
There are several ways to accomplish this sort of thing. You can make arrays of checkboxes, with or without named elements, like this:'
<input type="checkbox" name="color[orange]" />Orange
<input type="checkbox" name="color[green]" />Green
You can also provide type=hidden form elements with the same names as the checkbox elements. The last form element of the same name is the one that will be presented with the request. By doing this you can always have a predictable number of elements. The hidden value will be in the request if the checkbox is not fired. The checkbox value will be there if the client selected the checkbox.
Try setting up a form that submits your checkbox tests to a PHP script that says this (shown here in its entirety)
<?php var_dump($_POST);

Is this a nice way to preserve a field value when an HTML form submitted?

I have a form with two submit buttons.
The user fills field-A and hits submit.
Done that, some input fields will be filled with data.
After that first submission, the value on the field-A should not disappear.
How can we preserve this value after the first submission?
Should we, on the field-A value attribute, place:
value="<?php echo isset($_POST['fieldA'])) ? $_POST['fieldA'] : ''; ?>" ?
The form submits to self.
Update - Additional details:
This is a form that will have two submit buttons on the same page (sort of speak).
Submit Button A - Will grab some data based on a input field, and fill the other input fields on that form.
Submit Button B - Once the form is filled, it will use all that data to do another submission.
This is a very simple case, no frameworks are in place here. I do have, however, some sort of MVP structure here.
Thanks in advance,
MEM
In general, such things being done using 2 forms, no one.
And GET method, not POST. At least for the first form.
But as you cannot ask a question, it's impossible to give you an answer.
Here you go:
index.php
<form action=edit.php>Enter name: <input name="name"><input type=submit></form>
edit.php
<? $row = dbget("row","SELECT * FROM domains WHERE name = %s",$_GET['name']); ?>
<form method="POST" action="save.php">
Edit data for <?=htmlspecialchars($row['name'])?>:</br>
NS: <input name="ns" value="<?=htmlspecialchars($row['ns'])?>"><br>
Another: <input name="another" value="<?=htmlspecialchars($row['another'])?>"><br>
<input type="hidden" name="name" value="<?=htmlspecialchars($row['name'])?>"><br>
<input type=submit>
</form>
save.php
do whatever you do usually to save info
I would store these values into $_SESSION, as user fabrik said. This way they can be stored across the entire form submission process(assuming it is multiple pages) and posted all at once at the end.
Assuming you're having some kind of submission system with a "next" button to go to the next set of forms, using session_start() and $_SESSION is certainly the best method. More information could be found here, or various tutorial sites--
http://php.net/manual/en/reserved.variables.session.php
It's ok to do that with $_POST, some people dont like the ternary operator but for me it works just fine. Although, there are better ways to deal with forms using O.O.P. You could create a class that manages your form, and pass an array to the constructor of that class (eventually you could pass the $_POST) and the class will create your form according to the info submited. You could even use the same class to valdidate your form
I don't see the need of using $_SESSIONS, cause this is not information that you need to preserve during the whole session.. or not?
Try this:
<?php
$fieldA = (isset($_POST['fieldA']) ? $_POST['fieldA'] : '')
?>
// and in your form
<INPUT type="text" name="fieldA" id="fieldA" value="<?=fieldA?>" />
as you mentioned, this should work.

Categories