PHP - Retrieving $_GET variable after submitting form and change URL - php

I have the following form I want to use to filter through products on my website:
<div class="top-filter-select-container">
<form method="GET" action="" id="sort-filter-pick">
<select class="selectpicker" id="sort-filter">
<option value="popularity">Sort by Popularity</option>
<option value="ratings">Sort by Ratings</option>
<option value="newest">Sort by Newest</option>
<option value="lowest">Sort by Lowest Price</option>
</select>
</form>
</div>
I am trying to reload my page when an option is selected using jQuery form.submit() and retrieve the selected option to be used for filtering with a SQL query. I would eventually want to use this value along with other filtering values for a more complex filtering.
$(function(){
$('#sort-filter').on('change', function() {
var action = $(this).val();
$("#sort-filter-pick").attr("action", "?sort=" + action);
this.form.submit();
});
});
To test my code, I am just trying to echo isset($_GET['sort']) ? $_GET['sort'] : null;
The code works if I change form method to POST instead of GET but doesn't work with GET. On websites such as Amazon, the GET form method is used when applying filters from a select option but I also notice that the ?sort=... is added to the page URL after the form is submitted, which is not the case for me if I use GET. I was wondering what would be the right approach to do the same thing.

If you add a "name" to your form-elements you don't need to manually add the sort-criteria with jQuery.
HTML:
<div class="top-filter-select-container">
<form method="GET" action="" id="sort-filter-pick">
<select class="selectpicker" name="sort" id="sort-filter">
<option value="popularity">Sort by Popularity</option>
<option value="ratings">Sort by Ratings</option>
<option value="newest">Sort by Newest</option>
<option value="lowest">Sort by Lowest Price</option>
</select>
</form>
</div>
Javascript:
$(function(){
$('#sort-filter').on('change', function() {
this.form.submit();
});
});
Or you could just use location.href = url rather than posting the form.

Related

How to pass select value to form action using PHP?

I'm trying to make a simple search for Wikipedia where I can type what I want to search and a select where I can select the language. What I'm trying to do is to get the select value to be able to search in different languages so I just replace the language string in the url of wikipedia.org
(e.g. If I select French in the select dropdown the form should redirects me to fr.wikipedia.org and if I select English, it should redirects me to en.wikipedia.org)
Here's what I tried so far:
<form action="https://<?php $_POST["language"] ?>.wikipedia.org/w/index.php">
<input name="search" type="text" />
<select name="language">
<option value="en">English</option>
<option value="fr">French</option>
</select>
</form>
Now, on submit I get this url: https://.wikipedia.org/w/index.php?search=cat
How to pass select value to form action so I can add it at the start of the URL?
The reason your current script isn't working is because PHP gets processed when the page is loaded, not after you submit the form. The first time you go to this page, $_POST['language'] isn't set, so the form action gets set to https://.wikipedia.org/w/index.php. Then if you submit the form (get) you'll end up at https://.wikipedia.org/w/index.php?search=cat&language=en.
Instead what you need to do is process the form submission on your page, and then redirect to Wikipedia. By default, when you submit a form (with a default method of get) you'll end up at a page like /index.php?search=cat&language=en. So now you can read in those $_GET parameters to construct the URL to redirect to.
<?php
if (isset($_GET) && count($_GET)) {
$language = $_GET["language"];
$search = $_GET["search"];
$action = "https://".$language.".wikipedia.org/w/index.php?search=".$search;
header('Location: '.$action);
}
?>
<form>
<input name="search" type="text"/>
<select name="language">
<option value="en">English</option>
<option value="fr">French</option>
</select>
</form>
Another way would be to set <form method="post"> and then in PHP use $_POST like:
if ($_POST) {
$language = $_POST["language"];
$search = $_POST["search"];
$action = "https://".$language.".wikipedia.org/w/index.php?search=".$search;
header('Location: '.$action);
}
JS will make it a lot easier than PHP.
EDIT: This is only for your specific usage. If you want a more general way to do this using PHP instead of javascript, look at the answer by #WOUNDEDStevenJones
<input id="srch" type="text" />
<select id="lang" name="language">
<option value="en">English</option>
<option value="fr">French</option>
</select>
<button onclick="search()">Search!</button>
<script>
function search() {
var term =document.getElementById("srch").value;
var lang = document.getElementById("lang").value;
var link = "https://"+lang+".wikipedia.org/wiki/"+term;
location.replace(link);
}
</script>

Append URL extension to from action

I have a form which posts to a preset url variable, I'd like to add an extension to that url by using a dropdown selector:
<form class="my-form" method="POST" action="<?php echo $url; ?>">
<select name="script_to_follow">
<option value="script1.php">Report 1</option>
<option value="script2.php">Report 2</option>
</select>
Does anyone know how to add the value selectors as extenstions to the URL, for example if $URL= www.example.com and Report 1 was selected the resulting action would be to post to www.example.com/script1.php
You May have to do this using jQuery:
var url = 'www.example.com';
$(".script_to_follow").change(function(){
var selvalue = $(this).val();
url = url + '/' + selvalue;
window.location = url;
})
You can do it by using jQuery.
On Submit call a function:
var action = $('form.my-form').prop('action');
var selectedOption = $('select[name="script_to_follow"]').val();
$('form.my-form').prop('action', action+'/'+selectedOption;
You have two options here:
Use javascript to listen for change events on the <select> field, and change the action of the form based on what's been selected. This is what the other answers are suggesting.
To you avoid using javascript, instead of pointing the form towards different php scripts based on the selected value, have a single php script that switches based on the selected value. So:
<form class="my-form" method="POST" action="action.php">
<select name="script_to_follow">
<option value="a">Report 1</option>
<option value="b">Report 2</option>
</select>
And then in action.php do something like:
switch ($_GET["script_to_follow"]) {
case "a":
// contents of script1.php
case "b":
// contents of script2.php
}
simply try this
add id attribute to select box as
<select name="script_to_follow" id="script_to_follow">
<option value="script1.php">Report 1</option>
<option value="script2.php">Report 2</option>
</select>
now write some jquery codes to change action attribute with change in option
<script>
$('#script_to_follow').change(function(){ // onchange event
var url = $('#script_to_follow').val(); // get selected option
$('form.my-form').prop('action',url); // replace action attribute
});
</script>
Note : do not forget to include jquery script before form
<script
src="https://code.jquery.com/jquery-3.1.1.js"
integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
crossorigin="anonymous"></script>

how to submit php post data with jquery

I have a form with action attribute as searchbycat.php. in the form there is a selection field based upon which contents in the php page will be dynamically made. so I am passing the selected value by GET and processing the value in searchbycat.php. so I am implementing jQuery's click event when the user clicks the submit button and changing the action attribute value with the selected value from the drop down menu. but it does not seem to work. I searched for this in stackoverflow and found that it can be done in jquery ajax call. but those answers is not really helping me. can somebody please explain how to do this?
here is my code:
<form action="" id="form1" method="POST">
<select name="category">
<option>Search By Category</option>
<option value="mobile">Mobile Phone</option>
<option value="computer">Computer Electronics</option>
<option value="book">Books</option>
<option value="fashion">Fashion and Beauty</option>
<option value="furniture">Furniture</option>
<option value="house">House Rent</option>
<option value="vehicle">Vehicle</option>
</select>
<input type="submit" name="submit" id="search" value="Search"/>
</form>
and here is the Jquery part I am trying to do:
<script type="text/javascript">
$(document).ready(function(){
$('#search').click(function(){
$('#form1').attr("action","searchbycat.php?category=<?php echo $_POST['category']?>");
});
});
Just change your form to method = 'GET' and action="searchbycat.php"
It will send automatically like you want. You don't really will need the jquery in this situation

How to create a text box after selecting an option from drop-down list?

I'm trying to create a drop-down list with four options such that if I select the 4th option, I want a text box created so that I can get the value typed in that box using "$_GET"
Something like this;
<select name="value">
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
<option value="value3">Option 3</option>
<!-- And a 4th one -->
</select>
And if the 4th one is selected, a box should appear like this;
<input type="text" name="firstname">
Edit;
My current code;
<script>
jQuery(function($){ //calling the code inside braces when document loads and passing jQuery object as '$' parameter;
$("select[name='sortby']").change(function(){ //binding an event that fires every time select value changes
var select = $(this); //caching select, which value was changed
if(select.val() === "byDefindex"){ //checking if we selected the right option
$("<input>").attr({type: "text", name: "defindex"}).appendTo(select.parent()); //creating new input element object, setting its value to "value4" and appending to select parent element or wherever you want it
}
});
});
</script>
<form action="<?php $_PHP_SELF ?>" method="GET">
Select:
<br />
<select name="sortby">
<option value="playHours">Play Hours</option>
<option value="lastLogin">Last Login</option>
<option value="byDefindex">By Defindex</option>
</select>
<br />
<input type="submit" />
</form>
If your 4th option is this:
<option value="value4">Option 4</option>
You can use jQuery to display the field.
Put your field in a <div>
<div id="field"><input type="text" name="firstname"></div>
Now,
<script type="text/javascript">
$(document).ready(function(){
$('input[name="value"]').change(function(){
var v = $('input[name="value"]').val();
if(v=="value4") $('#field').show();
else $('#field').hide();
})
})
This is usually done via javascript; something like this (by using popular JavaScript library, jQuery) :
jQuery(function($){ //calling the code inside braces when document loads and passing jQuery object as '$' parameter;
$("select[name='value']").change(function(){ //binding an event that fires every time select value changes
var select = $(this); //caching select, which value was changed
if(select.val() === "value4"){ //checking if we selected the right option
$("<input>").attr({type: "text", name: "firstname"}).appendTo(select.parent()); //creating new input element object, setting its value to "value4" and appending to select parent element or wherever you want it
}
});
});
Hope that helps. You can find more here jQuery site
I'm not certain this is what you're asking, but it seems you're wanting to add new lines to your select list?
I often do something similar to this for adding new options to lists. The first option would be 'add a new record', like this:
<select name="value">
<option value="-1">Add New Option</option>
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
<option value="value3">Option 3</option>
</select>
Note that the value for "add new" is -1... you could put anything here, but it should be something that would never show up in the other options, so your javascript knows what to do when it is selected.
Add a 'onchange' to the select box like this:
<select name="value" onchange="if(this.value == -1) addOption(this);">
Note that if the selected option is -1, then a javascript function is called. It references itself (this), so that your function knows who called it.
Then create a function that allows adding a new option:
function addOption(theSelectElement){
// create a text box, underneath the select box:
var newInput=document.createElement('input');
newInput.type='text';
theSelectElement.parentNode.insertAfter(newInput,theSelectElement);
}
You'll want to add more code to this function so that the new text field has a name and perhaps an ID.
Hope this helps, or at least points you in the right direction.

Dependable dropdown menus with jQuery, PHP and SQL

this weekend i've been trying to use this script To create dependable menus.
It consists of an sql table with three rows: "ID, Master, Name" It later grabs the entries that contain 0 as the "master" and will use the resulting data to populate the first option list
To populate the next selection lists from the database, it uses a combination of the following JS and php:
and the rest of the select lists will populate accordinly.
The problem that i'm having is that After it populates the select lists I would like to have the visitors of the website hit a seach button to perform a search based on the data collected. The problem is that when I submit the form it sends the info stored in the "master" row of the database instead of the info on "name"
I'm Getting
index.php?genre=1&fruit=37&colour=39
Instead of
index.php?genre=Male&fruit=Strawberry&colour=Red
I tried to switch '.$row['name'].' to '.$row['id'].
But that was a no go, I also tried to only use '.$row['id'].' and it just messed up with the forms. Is there anyway I can accomplish what i'm looking for so that i can send the values selected on the fields to the url?
Thanks in advanced for any help on this one.
The behavior that you mentioned is normal as submitting a form automatically sends the value, instead of the text, of the selected option. The switch that you mentioned ('.$row['name'].' to '.$row['id'].)should work fine. If it is messing up the forms, please provide more information on what you mean by messing up the forms.
Otherwise, here is a possible solution. It's not the most elegant solution and is probably best suited for simple forms that do not require further complexities but basically, generate the querystring and redirect manually. This is based on the original example that you linked to at http://www.ssdtutorials.com/tutorials/series/dependable-dropdown.html.
JS:
var formObject = {
run: function (obj) {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
var id = obj.attr('id');
var v = obj.val();
jQuery.getJSON('http://jquery-dependable-dropdown.ssdtutorials.com/mod/update.php', {
id: id,
value: v
}, function (data) {
if (!data.error) {
obj.next('.update').html(data.list).removeAttr('disabled');
} else {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
}
});
}
};
$(function () {
$('.update').live('change', function () {
formObject.run($(this));
});
$('#submitButton').click(function () {
window.location.href = 'test.php?gender=' + $('#gender').find(':selected').text() + '&category=' + $('#category').find(':selected').text() + '&colour=' + $('#colour').find(':selected').text();
});
});
HTML:
<div id="wrapper">
<form id="theForm" action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<select name="category" id="category" class="update" disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update" disabled="disabled">
<option value="">----</option>
</select>
<input type="button" id="submitButton" value="submit">
</form>
http://jsfiddle.net/BUJnf/1/
Hope that helps a bit!

Categories