advanced search without javascript - php

I'm building an advanced search with a-tags to filter for first letter abcdefghijklmnopqrstuvwxyz0-9 and also an input field, options fields for other criteria, radio buttons and a submit button. When I click on a letter-filter, it sends it as $_GET variable. But when I then use the input fields it forgets it of course. How can I grab this variable with the submit button before sending it along with all the other variables from the form? Do I have to use JS and AJAX for that? Do you recommend that?
EDIT
so let me rephrase that.
I have different variables to send to the server, coming from input fields, radio buttons, option fields but I also want a link for each letter of the alphabet (so it would then list all entries that start with that letter).
When I click the submit button it sends all the variables from the input fields but not from the a-tags (cause they are not recognized as form-fields I guess). When I click on the a-tags (a letter) it sends just that very variable to the server which is fine as well. My question is, how can I get the submit button to send everything?
<input type='search' id='search-query' name='q' class='uk-input uk-form-width-medium' placeholder='Suche'>
<p>
<?php
foreach ($alphabet as $abc){
if ($abc == $letter) {
$class = 'current';
}
else $class = '';
echo '<a class="'.$class.'" href="'.$page->url.'?letter='.$abc.'">'.$abc.'</a> ';
}
?>
</p>
<select class="uk-select uk-width-medium" name="what">
<option>Titel</option>
<option>Autor</option>
<option>Erscheinungsdatum</option>
</select>
<label><input class="uk-radio" type="radio" name="how" value="aufsteigend" checked> aufsteigend</label>
<label><input class="uk-radio" type="radio" name="how" value="absteigend"> absteigend</label>
<button class="uk-button uk-button-primary" type="submit">Suche starten</button>
</form>```

I assume you want to have dynamic Google-like search where you type in "a" and it gives you a drop-down list of options like "airplane, applle, artery" etc.
If that is the case, then yes, you do need JS + AJAX.
Instead of clicking on a letter filter, you can have AJAX dynamically display you the options available right in the input field.
Given the vague description of your question and the absence of images of your UI that is all that can be said.

I didn't really get the question and the whole situation from the explanation, but sounds like following:
You want to render the hints based on the value of the input field search-query when user clicks on the specific button: letter-filter. If this is right, then you will have to anyways send a get request to the back end so that it would give back the page with all hints.
FE:
<html>
<body>
<form action="app.com/myurl" method="GET" >
<input id="letter" value="a" name="letter" />
<input id="letter2" value="b" name="other_param" />
<input id="letter3" value="c" name="another_param" />
<!-- All three inputs will be visible in the $_GET variable when you send the request -->
<!-- Other input fields here: <input type="whatever" id="whatever".../> -->
<button type="submit">letter filter</button>
</form>
</body>
</html>
You can even track the request in borwser's network tab, if the params are not appended as query params like app.com/myurl?letter=a&other_param=b&another_param=c, if you dont see the query params but see the url itself, then I can suggest you forgot to set the method of the form.
But I am still not sure, can you rephrase your question, as it doesn't clearly explain the case, sorry your english is a little confusing.
EDIT AFTER Rephrase:
I understood your aim now and you are right, submit button sends only form fields and <a> tag is not a form field.
If you want to append all form fields to <a> tag click then you have few options.
Append all parameters on server side manually on render:
You have
foreach ($alphabet as $abc){
if ($abc == $letter) {
$class = 'current';
}
else $class = '';
echo '<a class="'.$class.'" href="'.$page->url.'?letter='.$abc.'">'.$abc.'</a> ';
}
And you need to additionally add form fields as well, I assume on first time click when none of the tags are rendered (no <a> tag on the screen) then you just send the form data, in tha moment you catch form data from $_GET and append to anchor
foreach ($alphabet as $abc){
if ($abc == $letter) {
$class = 'current';
}
else $class = '';
echo '<a class="'.$class.'" href="'.$page->url.'?letter='.$abc.'otherParamName='.$_GET['otherParam']].'">'.$abc.'</a> ';
}
You can use js, to collect form data, I guess you use jQuery, and append to the href on click of the anchor
jQuery('a.someClassIdentifier').click(fuction(e) {
// Please read documentation of jquery how to handle click events, I dont remember it out of my head right now.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
But as an ultimate answer I would say rethink your approach. If you have already a form, and it sends GET request to the endpoint and it returns the same page where tags are visible then you can use form fields instead of anchor tags, that would already handle the data sending for you. But if you have different endpoints for tags receiving then best will be to send ajax request to receive only json data and render them without refreshing the page.
Hope it helps.

Related

Passing variable from html input to included php file

I have situation where I have an accordian and I am referencing a php file gridlist.php within another php file displayvar.php. In other words the context of displayvar.php are shown in the webpage gridlist.php. Now gridlist.php has a checkbox input:
<input type="checkbox" id="foodlike" value="icecrm">I like ice cream</input>
<input type="checkbox" id="foodlike" value="pizza">I like pizza</input>
<input type="checkbox" id="foodlike" value="soda">I like soda</input>
Now when I check on the checkboxes in the table referenced by gridlist.php displayvar.php should be able to display a list of the items checked. For instance it should display if all three checkboxes are checked:
icecrmpizzasoda
If the last one is checked then only soda should be displayed. Keep in mind because this displayvar.php is displayed within the context of the website gridlist.php I used the following command in gridlist.php:
<?php include 'displayvar.php'; ?>
I tried in the displayvar.php to obtained the variables foodlike (as defined by the variable id in the checkbox gridlist.php) from gridlist.php and then echo them based on this snippet of code:
<?php
$like=$_POST['foodlike'];
echo "$like";
?>
How can I tweak this code to get my desired result?
You can achieve this with :
gridlist.php
<form method="post" action="displayvar.php">
<input type="checkbox" name="icecrm" value="icecrm">I like ice cream</input>
<input type="checkbox" name="pizza" value="pizza">I like pizza</input>
<input type="checkbox" name="soda" value="soda">I like soda</input>
<input type="submit" value="Submit">
</form>
displayvar.php
<?php
$icecrm = isset($_POST['icecrm']) ? $_POST['icecrm'] : null;
$pizza = isset($_POST['pizza']) ? $_POST['pizza'] : null;
$soda = isset($_POST['soda']) ? $_POST['soda'] : null;
echo is_null($soda) ? $icecrm.$pizza : $soda;
?>
As you mentioned you did not want a submit button, you'll probably want some sort of "interactive", instant solution and bypass going to the server, i.e. bypass PHP. Since the include 'foo.php'-statement effectively dumps all contents of foo.php into the current file (you could say it "merges them into one"), all interactions happen on the same page. Thinking about your setup as "file A is communicating with file B via the server" is wrong - there is only one file/page.
So, having said all this, my proposed solution uses Javascript and the seemingly omni-present jQuery library, which you will have to include in your page. The snippet below binds an event-handler to the inputs' change-event, which is triggered when a checkbox or radio are checked or the value of a text-input is changed. Then, we append the checked value to a dummy container for display.
$(function() {
var $likes = $('#likes');
// bind event handler to all input-elements
$('input').on('change', function() {
var $input = $(this),
oldText = $likes.text();
if ($input.is(':checked')) {
$likes.append($input.val());
} else {
$likes.text(oldText.replace($input.val(), ''));
}
});
});
label {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="icecream">
<input type="checkbox" name="icecream" id="icecream" value="icecrm">I like ice cream</label>
<label for="pizza">
<input type="checkbox" name="pizza" id="pizza" value="pizza">I like pizza</label>
<label for="soda">
<input type="checkbox" name="soda" id="soda" value="soda">I like soda</label>
<span id="likes"></span>
Edit: This is how I would lay out the "root" file containing the two gridlist.php and displayvar.php, along with the Javascript required to manipulate the DOM:
<html>
<head>
<title>Test</title>
<style>
label {
display: block;
}
</style>
</head>
<body>
<!-- This will be in a file you called 'gridlist.php' -->
<label for="icecream">
<input type="checkbox" name="icecream" id="icecream" value="icecrm">I like ice cream</label>
<label for="pizza">
<input type="checkbox" name="pizza" id="pizza" value="pizza">I like pizza</label>
<label for="soda">
<input type="checkbox" name="soda" id="soda" value="soda">I like soda</label>
<!-- // -->
<!-- This will be in a file you called 'displayvar.php' -->
<span id="likes"></span>
<!-- // -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $likes = $('#likes');
// bind event handler to all input-elements
$('input').on('change', function() {
var $input = $(this),
oldText = $likes.text();
if ($input.is(':checked')) {
$likes.append($input.val());
} else {
$likes.text(oldText.replace($input.val(), ''));
}
});
});
</script>
</body>
</html>
Edit 2:
You still seem to be having problems, so I shall try to clarify why I think you are not succeeding.
Using only PHP, it is not possible to access the value of a checked checkbox without submitting the form back to the server.
To retrieve the value of a checkbox that has been checked by the user, you essentially have only two possibilities.
Option 1: Submit the form using POST/GET
This entails you having a <form> element enclosing the inputs along with a submit button for submitting the form. This is how (probably) 98% of forms on the Internet work. The data in the form is sent, using either the POST or GET method, to the script you specify in the form-tag. Consider this as an example (text omitted):
<form action="handler.php" method="get">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<button type="submit"></button>
</form>
When the user clicks the submit-button, the form is sent to handler.php via the GET method. There, the form data will be available in the $_GET array. Same applies for POST. Now, an often-used approach is to submit the form to the same script via action="#", meaning you need not have a dedicated handler, but can process data within the same script as your form. Obviously, you will have to distinguish two cases: one initial case where no data is set in $_GET/$_POST, and one submission-case when the data is set.
The same applies to data stored in the $_SESSION, btw: again, you will have to tell a server-side script to put the data you want in the user-session; only then will you be able to retrieve it again.
A similar approach I would call "Option 1 b)" is submission via AJAX. This is basically form submission without leaving/reloading the page. Sending the data is done via Javascript and an "XMLHttpRequest". An XHR lets you send any type of data, not only XML. Again, similar logic applies: you serialize the data in some way, provide an endpoint, usually a script, to talk to, and communicate the data to that script via POST/GET. Then your script can handle the data and return a response, which will be available in the JS that initiated the AJAX-request.
Option 2: By accessing the DOM directly
The DOM is the "tree" that is made up of the HTML-elements of your page. Using Javascript, one can access and modify these elements, remove specific ones or add new ones. This API used to be implemented quite differently across browsers, which is why libraries like jQuery or Prototype were created: they provide a unified API across different user agents.
We can use two features of these libraries:
respond to (user-triggered) events
access elements and data stored therein
This is the approach I used in my answer, which I will not repeat here and you can read above. We respond to the event of the user clicking on a checkbox, and access that very checkbox to retrieve the value-data and process it further.
TL;DR
You have two options: submit the form to a script and process the data there; or, manipulate the DOM to catch user-events and pull out the values.
Credit: this is summing up every answer and comment in this thread, especially those of Obsidian Age and Valentin Papin, who both gave great answers that would lead to a clean and functional result.

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---

Why does my form submit to my php as a url instead of the actions in the php file

Ok I have a form with multiple submit buttons.
The coding on my php file has a header with a url depending on which form was entered. My issue is when I submit the form( no matter which button I use) the window that pops up is not the url action assigned to that button but the php file itself. What am I doing wrong?
the form starts of like this so that you can see if I directed it correctly
<form method="post" action="http://gamerzacademy.com/foodCYO.php" target="_blank">
<input type="text" name="uid">
<input type="submit" name="Dish1" value="Dish1" onclick="
this.disabled=true;
this.value='Gift Opened';
document.FreeFoodForm.submit();">
<input type="submit" name="Dish2" value="Dish2" onclick="
this.disabled=true;
this.value='Gift Opened';
document.FreeFoodForm.submit();">
etc......
now the php file starts like this
<?php
if ($_REQUEST['Dish1'] == "Dish1") {
header("Location: url1".urlencode($_POST['uid']));
}
else if ($_REQUEST['Dish2'] == "Dish2") {
header("Location: url2".urlencode($_POST['uid']));
}
else if ($_REQUEST['Dish3'] == "Dish3") {
header("Location: url3".urlencode($_POST['uid']));
}
.....etc
?>
You are posting the form through Javascript. The code doesn't know which button was clicked, so the value of that button isn't posted to the form. Therefor, your form cannot see which button was clicked. If you change the method to get, you will see which value do or do not get posted.
I think you don't need to post from Javascript at all. Just let the button do the posting. Only the name and value of the button that was clicked will be posted.
B.t.w., you disable the button, presumably because you don't want people to press the button twice, but in your setup they still can press any other button. I think it is wise to disable all of them.
Two things:
First, make sure the URLs you are sending in header are valid URLs.
Second, it looks like you have some whitespace before the <?php opening tag. Make sure there is no whitespace before the PHP opening tag. If there is, header won't work.
By doing the following in JavaScript:
this.disabled = true;
You effectively don't send its value to PHP.
A better idea might be an on submit handler in the form that prevents double submit.

php post via html <a> tags

I have built a site using php and want to try keep it one page.. The site displays pictures and so far i have it making links from folders in a folder each folder contains images so what i want is to make a post/get tag in the url and when the page loads it uses this to get the images from that folder.
So I want to use the generated links to post to the same page with a value via self_post is this possible and if so how?
my get section is
if(empty($_post['foldername']))
{
$directory = "portfolio/homepage/";
}
else if(isset($_post['foldername']))
{
$foldername = $_post['foldername'];
$directory = "portfolio/".$foldername."/";
}
and my link is like this
echo '<li><a id="" class="" href="'.$_SERVER["PHP_SELF"].'">'.$b.'<input type="hidden" name="foldername" value="'.$b.'" /></a></li>';
Thanks
What's wrong with GET?
Click me
The only way to make a POST request using a <a> tag would be to have it submit a form via javascript:
<form method="post" id="hidden_form" name="hidden_form" action="script.php">
<input type="hidden" name="foldername" value="<?php echo $b ?>" />
</form>
...
post me
You can also update the values of the hidden element(s) from javascript as well so when you click a particular link, it sets one of the values to something specific to the link.
The only way is doing it through JS. You can either send an AJAX request specifying POST, or you can create a hidden form and submit it. Here's an example
document.getElementById('my-link').onclick = function(){
// Code to submit the hidden form or to send an AJAX request specifying POST
return false; // to prevent the default behavior
}
I know of no way to do this with vanilla anchor tags. You could establish click event handlers in javascript to submit an XHR request. However, I have accomplished this in the past by using multiple form tags with a single submit entity (<input type='submit', <button type='submit', etc.).
Your forms would look like so:
<form action="{$_SERVER['PHP_SELF']}" method="post">
<input type="hidden" name="foldername" value="YOURVALUEHERE">
<input type="submit">
</form>
Like drew010 said if you absolutly need the POST method. Otherwise most single-page website uses things like index.php?a=1&b=2 where you can get "a" and "b" with $_GET["a"] ...

In PHP, How would I use a variable that was created in another php page?

I have an included page to the main index page, in the included page it has buttons to click on..i want to give these buttons a variable and when someone clicks on it, I can keep track of what button they selected in another page, which will show information for the selected button/variable...
Any ideas?
Well there is several ways to do this, but the main question is are you using a form button or a image button or a link or what?
Form:
HTML:
<form name="phpForm" action="myFile.php" method="get">
<input type="submit" name="button" value="1">
<input type="submit" name="button" value="2">
</form>
PHP:
<?PHP
echo $_GET["button"]; //either 1 or 2
?>
Image:
HTML:
<img src="whoo.png" />
<img src="hilarious.png" />
And the PHP above will also work with this.
You should really start reading a basic PHP tutorial.
Depending on what form is the method, you'll receive the variables in either $_POST or $_GET:
Use this code to find out
print_r($_GET);
print_r($_POST);
Welcome to web programming, this should get you started: http://www.w3schools.com/php/php_intro.asp
There are several ways of doing this you can either use GET, POST, or store the variable in a SESSION
I am assuming when user clicks the button it is directed to another page, if its true, then you can do a GET with http://yoursite.com/pageTo.php?data='hello' as the href that links to the button. Where pageTo.php would $_GET['data']
Insert the jquery code to try out the click counts:
$(document).ready(function(){
var count =0;
$('button').click(function(){
count = count +1;
$('#showcount').html('click count' + count);
return false;
});
});
and somewhere in your body make a div with id = ' showcount' to show the click counts.
Or you can then save the click count into a text file to look at...or whatever
I hope this give you some ideas...

Categories