Pass URL parameters to Select options with JavaScript and Php - javascript

I am kinda new in JavaScript and need some help.
I have a search form in my navigation menu.
Here is my code php+html for the form.
<form action="search.php" name="form-name" method="GET" enctype="multipart/form-data">
<div class="row">
<div class="col-lg-2 col-md-12 col-sm-12 search">
<label>Destination</label>
<select required name="country" id="destination" onChange="getCity(this.value);">
<option value="">Any destination</option>
<?php $query = "SELECT * FROM countries";
$select_region_query = query($con, $query);
while ($row = fetch($select_region_query)) {
$region_id = $row['country_id'];
$region_name = $row['country_name'];
echo "<option value='".str_replace("&", "and",$full_region)."'>$full_region</option>";
}
?>
</select>
</div>
<div class="col-lg-2 col-md-12 col-sm-12 search ">
<label>City</label>
<select name="city" id="city" onChange="get_dropdown_ajax(this.value);">
<option value="">Any Cruise Line</option>
<?php $query = "SELECT * FROM cities";
$select_city_query = query($con, $query);
while ($row = fetch($select_city_query)) {
$city_id = $row['city_id'];
$city_name = $row['city_name'];
$city_name_value = str_replace("&"," and ",$row['city_name']);
echo "<option value='$city_name_value'>$city_name</option>";
}
?>
</select>
</div>
<div class="input-group col-lg-4 col-md-12 col-sm-12 search">
<label>Dates</label>
<select name="date_1" id="date_1">
<option value="">Any Day</option>
<?php
for($i=0;$i<31;$i++){
$i = str_pad($i,2,"0",STR_PAD_LEFT);
echo "<option value='$i'>$i</option>";
}
?>
</select>
<select name="date" id="date">
<option value="">Any Month</option>
<?php
for ($i = 0; $i <= 36; $i++) {
$time = strtotime(sprintf('+%d months', $i));
$value = date('Y-m', $time);
$label = date('F-Y', $time);
$label = str_replace("-", " ", $label);
echo "<option value='$label'>$label</option>";
}
?>
</select>
<input type="hidden" id="datepicker">
</div>
<div>
<button type="submit" name="search" class="search_button_nav btn btn-info">
<span class="glyphicon glyphicon-search"></span></button>
</div>
</div>
</form>
What I need to achieve is when the user doing a search to get these URL parameters and use these to change my select options based on their choices.
e.g If they search for country United Kingdom on search page my dropdown on countries to display United Kingdom instead of Any Destination.
I tried to do that with php $_GET but I am not sure is a good idea, because my country list is really big and I can create for every country if(issets($_GET)=='United Kingdom)' etc..
Is that something can complete with javascript without have to check the query of url like i tried with php?
I seach for solution and I find on other posts that (window.location); probably can help me.
I tried to console.log(window.location) and I can see the parameters, but how can I split them properly and use them with php?
Any feedback would be helpful.
P.S My url is looking like this one : nameofmysite/search.php?country=+United+Kingdom&chk=1&city_name=%25date_1=05&date=July+2018

I am not sure whether I understand your problem If you just want to set the dopdown-item to the city the user is searching for, using $_GET is no bad idea. You just have to check whether the parameter is given, then you can use it in PHP.
if(isset($_GET['search'])) {
echo "<option value='".$_GET['search']."'>".$_GET['search']."</option>";
} else {
echo "<option value=''>Any destination</option>";
}

I think you are trying to mix the use of the parameter.
Once the request is sent, the server will process that request and interpret the PHP page in the server before send it to the client (the browser). If you need to check a parameter then you can get it with the global variable $_GET and do whatever you want and build your page conveniently.
Get request parameters from URL in PHP GET URL parameter in PHP
Once the page is built it is sent to the client wich interpret it and your browser renders it. Then you can get the URL with window.location and parse it conveniently with split method or Regular expressions to get what you want from there.
Get request parameters from URL in Javascript How to get URL parameters with Javascript?
But the page is already rendered and what you can do then is manipulate the DOM of the page.

Related

display data on another form after selecting the option

how, after I choose the option and then it will appear #formid where the form is filled in by the $stock as selected in the option section
<div class="form-group">
<label for="exampleFormControlSelect1">Nama Item</label>
<select class="form-control" id="exampleFormControlSelect1" name="itemId">
<option selected>Choose</option>
<?php $no=1; while($row = $result->fetch_object() ) {
$stock = $row->stock;
$i_name = $row->i_name;
$id = $row->id;
?>
<option value="<?php echo $id; ?>"><?php echo $i_name; ?></option>
<?php } ?>
</select>
</div>
the form that will appear after selecting the option
<div class="form-group">
<label>Stock</label>
<input class="" type="number" name="" value="<?php echo $stock;?>">
</div>
I am new in php and javascript, can you write with a neat code & easy to understand, thank you :)
If I understand you correctly, you want to show the second div onSelect of the first one.
Because of the fact, that you use bootstrap I assume
that you have already included jQuery if not you have to do that for this example.
You have to add this JavaScript on your page.
<script>
$( document ).ready(function() {
$( "#exampleFormControlSelect1" ).change(function() {
$("#secondDiv").show();
});
});
</script>
And you need an id on your div.
<div id="secondDiv" class="form-group">
<label>Stock</label>
<input class="" type="number" name="" value="<?php echo $stock;?>">
</div>
You will need javascript for this if you want the data to appear without the page reloading.
First we make Javascript Function that takes your option id and passes it to your input value.
funcction chooseOption(clicked.id){
document.getElementById('myInput').value = clicked_id;
}
HTML and PHP we need to add a different id for each option. The best way it to pass the option name you want for each. We also added our onclick function to the options.
<div class="form-group">
<label for="exampleFormControlSelect1">Nama Item</label>
<select class="form-control" id="exampleFormControlSelect1" name="itemId">
<option selected>Choose</option>
<?php $no=1; while($row = $result->fetch_object() ) {
$stock = $row->stock;
$i_name = $row->i_name;
$id = $row->id;
echo "<option onclick=\"chooseOption(this.id);\" id=\"".$stock."\" value=\"".$id."\">".$i_name."</option>";
<?php } ?>
</select>
</div>
Added an id to your input so javascript can send the data to it.
<div class="form-group">
<label>Stock</label>
<input id="myInput" class="" type="number" name="" value="">
</div>

Mysql query search based on variable input

I am quite new at coding such things as I am asking so I would appreciate if someone could perhaps help me out.
I am looking to do an MYSQL search and echo based on variables selected in a drop-down menu. I am not too sure on how to search 1 inputted variable let alone multiple based on the selected. I would like it to be a filtering system.
Here is my form:
<form>
<fieldset data-role="controlgroup" data-type="horizontal" data-mini="true">
<legend>Horizontal, mini sized:</legend>
<label for="select-h-6a">Select A</label>
<select name="select-h-6a" id="select-h-6a">
<option value="#">One</option>
<option value="#">Two</option>
<option value="#">Three</option>
</select>
<label for="select-h-6b">Select B</label>
<select name="select-h-6b" id="select-h-6b">
<option value="#">One</option>
<option value="#">Two</option>
<option value="#">Three</option>
</select>
<label for="select-h-6c">Select C</label>
<select name="select-h-6c" id="select-h-6c">
<option value="#">One</option>
<option value="#">Two</option>
<option value="#">Three</option>
</select>
</fieldset>
</form>
(would I need a submit button to send the query?)
Here is the code I am using to get posts at the moment:
$posts = getAllPosts();
<div id="searchpost">
<div class="ui-bar ui-bar-a">
<div id="postTitle">
<?php echo $posts[$p]["post_title"];?></div>
</div>
<div class="ui-body ui-body-a">
<div id="postContent">
<?php echo $posts[$p]["post_content"];}?></div>
</div>
</div>
and the functions for that:
function getAllPosts() {
require "config.php";
$posts = $c->query ( "SELECT * FROM posts" );
if ( $posts->num_rows > 0 ) {
while( $row = $posts->fetch_assoc() ) {
$postData[] = array( "user_id" => $row[ "user_id" ], "post_title" => $row[ "post_title" ], "post_content" => $row[ "post_content" ] );
}
} else {
return "No Data";
}
return $postData;
}
Posting the data:
<div id="postTitle">
<?php echo $posts[$p]["post_title"];?></div>
</div>
<div class="ui-body ui-body-a">
<div id="postContent">
<?php echo $posts[$p]["post_content"];}?></div>
</div>
However, as you can see, it calls for things in the database specifically. How can I make what I select in the drop down menus be shown instead of the specifics?
Can this be added for multiple selected options such as selecting rock, singer and 2 members showing only the records that all three of those in it? I assume if I don't want something specific in option 2 I can have an all option which searches for everything in that category.
My database: Image
Connection: (config.php)
<?php
$c = mysqli_connect( "localhost", "user", "pass", "database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
So, I need help with:
- putting the drop down options into variables
- having those variables be put into an MYSQL search query
I think the variables are the key here but I am not too sure on how to do it.
I hope you understand what I am needing help with. If not please ask questions :) Thank you so much xx

PHP noob having problems posting drop-down values into MySQL database. My table formatting is off too. Can anyone shed some light on this?

Building a football prediction website. I am getting thee Home_team names and away team a names from fixtures table in DBMS, with corresponding drop down boxes for each fixture so that the user can predict the score. I cant get it to work. Grateful for any help!
//establish connection
<?php
$connection = mysql_connect('localhost', 'root', 'password');
mysql_select_db('mls');
$query = "SELECT * FROM fixtures WHERE Fixture_ID BETWEEN '1' and '10' ";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if($num>0){
echo"<table>";
echo "<th>Home Team</th>";
echo "<th>Home Score</th>";
echo "<th>Away Score</th>";
echo "<th>Away Team</th>";
for($count=0;$count<$num; $count++){
$row = mysql_fetch_array($result);
echo"<tr>
<td>".$row['Home_Team']."</td>
<td>
<form id="myForm" method="post" action="process3.php">
<select name="Home_Score">
<select id='H".$count."'>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select >
</td>
<td>
<form id="myForm" method="post" action="process3.php">
<select name="Home_Score">
<select id='A".$count."'>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
<td>".$row['Away_Team']."</td>
</tr>";
}
echo"</table>";
<input type="submit" title="Submit the form">
</form>
}
?>
<html>
<?php
//process3.php file
<?php
include_once('db.php');
$Home_Score = $_POST['Home_Score'];
$Away_Score = $_POST['Away_Score'];
if(mysql_query("INSERT INTO user_prediction VALUES('$Home_Score', '$Away_Score')")){
$result = "Successfully Inserted";
else
$result = "Insert failed";
?>
//myscript.js file
?>
$("#sub").click(function(){
$.post( $("#myForm).attr("action"), $("#myForm:input").serializeArray(),
function (info){$("#result").html(info);});
});
$("#myForm").submit(function(){
return false;
});
While there is plenty of things that could be causing problems, notice here:
<select name="Away_Score">
//count id for unique values in dropdown
<select id='A".$count."'>
$count will literally be represented here as the string "$count", due to this code not being contained in PHP tags. Try correcting instances of code similar to this to something like below:
<?php
echo '<select name="Away_Score">';
//count id for unique values in dropdown
echo '<select id="A' . $count . '">';
?>
I see some problems there..
you switch between PHP and HTML appearently without knowing what
is what or how you start PHP and end it.
Your table is messed
up. You open a table, but in mid you just forget about it. you dont
close your td-tags or your table.
your select is messed up. You
have 2 select tags, one of which has even unescaped php-code written
in it.
your JS click-event does not trigger, because you named
it wrong.
Apart from you using mysql_-functions, which are deprecated and will stop working in newer PHP vewrsions, the list goes on...
In short: This code is a complete mess. Erasing this and starting all over with a clear head would be the best option.
To digress a bit, I honestly think that for an app of that size you should be employing some open source PHP packages. Sorry I can't comment yet so had to leave as an answer

OnChange option remain same after page refresh

I have this script for money conversion so user can choose it's currency from the list like Us to Euro so I want to make it remain same after page refresh like if user have chosen Euro and he refresh the page it should remain same.
Here is my Javascript and Code
<script>
function updatePrice(val) {
p = document.getElementById("original_price").value;
newp = p * val;
document.getElementById("calculated_price").value = newp;
}
</script>
Php Code:
<?php
$pr = 180;
?>
<select onchange="updatePrice(this.value)">
<option value="1">US</option>
<option value="98">RS</option>
<option value="61">Ind</option>
</select>
<input type="hidden" id="original_price" value="<?php echo $pr; ?>" />
Price: <input type="text" id="calculated_price" value="<?php echo $pr; ?>" />
Update 1 After Implementing Session
<?php
session_start();
// store session data
$_SESSION['value']=".updatePrice(this.value).";
if(isset($_SESSION['value']));
?>
<?php
$pr = 180;
?>
<select onchange="<?php echo $_SESSION['value']; ?>">
<option value="1">US</option>
<option value="98">RS</option>
<option value="61">Ind</option>
</select>
<br>
<hr>
<input type="hidden" id="original_price" value="<?php echo $pr; ?>" />
Price: <input type="text" id="calculated_price" value="<?php echo $pr; ?>" />
<script>
function updatePrice(val) {
p = document.getElementById("original_price").value;
newp = p * val;
document.getElementById("calculated_price").value = newp;
}
</script>
Actually PHP dosent offer any viewstate mechanism, as far as i know , So what you can do is store this in some hidden field.The best way and my personal recommendation is to use a session variable for this purpose
http://www.w3schools.com/Php/php_sessions.asp
And if you need to solve this issue using javascript, You can use Cookies too
http://www.w3schools.com/js/js_cookies.asp
I have done this using jquery and javascript by setting a cookie, hence i dont want you to get confused with jquery plugin for cookie. You can do this in a much more simpler way using jquery plugin for cookie.
Here's the code
HTML
<select id="selectCurrency">
<option value="1">US</option>
<option value="98">RS</option>
<option value="61">Ind</option>
</select>
jquery/javascript
$(document).ready(function(e){
var name = "Currency=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++){
var c = ca[i].trim();
if (c.indexOf(name)==0) $('#selectCurrency').val(c.substring(name.length,c.length));
}
});
$('#selectCurrency').change(function(e){
var cookieVal = "Currency="+$(this).val();
document.cookie = cookieVal ;
});
Fiddle
http://jsfiddle.net/AmarnathRShenoy/HM3Zj/
You can use session or store the selected values somewhere in database, inUpdate price function make an ajax call which stores, your selected value and keep pdating at, on onchange event. now, each time your page gets refreshed, the previuosly selected value will get fetched from the database and you can show it seleted.

Javascript: Sustaining Selected Index of a ComboBox on Search

I have a problem with my javascript. First of all here is my code partitions:
<select class="inputTxt" style="width: 120px;" id="yearCombo" name="yearCombo">
<option value="0">2013</option>
<option value="1">2012</option>
<option value="2">2011</option>
</select>
function searchClicked() {
var operationField = document.getElementById("<%=FeedbackReportCtrl.PARAM_OPERATION%>");
operationField.value = "<%=FeedbackReportCtrl.OPERATION_SEARCH%>";
var yearFilter = document.getElementById("<%=FeedbackReportCtrl.PARAM_YEARFILTER%>");
yearFilter.value = document.getElementById("yearCombo").options[document.getElementById("yearCombo").selectedIndex].text;
var mainForm = document.getElementById("main");
mainForm.submit();
}
Here what goes wrong is the following;
For example, when I choose the year 2011 from the combo box and then hit the search button, it brings me the desired results;however, the selected index of the box returns back to 2013. How can I sustain my selection after search function?
The issue you have isn't a javascript one. When you submit a form you refresh the whole page, removing any client-side (user or javascript) adjustments to it.
It should be set by the php/java that is generating the page you post your form to, to set a selected="selected" or relevant, based on the value you just posted.
In php this would be
if($_POST['year'] == '2013') echo ' selected="selected"';
In java or jsp there are similar ways of doing this. Javascript itself could do the same probably.
Submitting the form refreshes the page (unless done via AJAX), thus returning to the default selected value, i.e the first one.
To overcome this you need to send along with the form the chosen year - assuming that you are self-submitting - and explicitly mark this year as the selected option.
In PHP Your code would then be something like:
<?php $year = $_POST['year']; ?>
<select class="inputTxt" style="width: 120px;" id="yearCombo" name="yearCombo">
<?php for ($i=2013;$i>2010;$i--): ?>
<option value="<?php echo $i; ?>" <?php if ($year==$i) echo "selected"; ?> >
<?php echo $i; ?>
</option>
<?php endfor; ?>
</select>

Categories

Resources