Combined select and load the page - php

I have a normal form with the combined selects for country and city, when I send the form no problem, but when I come back to the form for correct the mistakes I can't see the city I selected and the page didn't let me see the rest of the select. The script is:
$(document).ready(function(){
$("#country").change(function(event){
var id = $("#country").find(':selected').val();
$("#city").load('1select.php?id='+id);
$("#city").html(options);
$('#city option:first').attr('selected', 'selected');
});
});
I try with the ctrl+shift+k (I don't remember the name) in Firefox and the only error is "jquery is not defined". I don't know what's wrong with the code.

"to make sure you have the history of your selected values when you return to your form, you can use php as below (I may make some syntax errors as I am not PHP dev)
<select name="city">
<option value="birmingham" <?php if (isset($_POST['city']) && $_POST['city'] =='birmingham'){ ?>> selected <?php } ?>Birmingham </option>
</select>

Related

Get selected option in php without pressing submit

How to get the value of the selected option in php
<select id="select" name="select">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
</select>
PHP is a server-side language. So without submitting anything to the server, you can't find what option has been selected. However, if you want to find it with JavaScript or the jQuery library, you could do something like this:
Using vanilla JavaScript:
document.getElementById("select").onchange = function() {
// find what option the user changed to!
var option = document.getElementById("select").value;
// alert with the option
alert("Select changed to: " + option);
};
Using jQuery library:
// uses jQuery's .change() for a <select> element
$("#select").change(function() {
// find what option the user changed to!
var option = $("#select option:selected").text();
// alert with the option
alert("Select changed to: " + option);
});
You have to make a php file which creates a database table( mysql or mariadb can be used) then in that table you have to redirect the value of form by assigning the php file to the action button and then the value of that option will get restored in that database.
I will prefer to use phpmyadmin, you can create database in it without code and can link it to your file. But if you want to really learn this then i will suggest that first learn php and mysql from a decent website like w3schools because if you simply copy the code than you will not understand anything.
PHP is serverside programming language and it can get values from post , get and cookies and ... . you have to submit form to send values through GET or ... . Best way to do this is using ajax .
`$('#select').on('change',function(){
$.ajax(
/* your code here */
);
}).

Get options for select in forms from database

I'm programming the server side using PHP and got stuck.
I want to create a set of input fields using select tags for a form.
The options for the select should be fetched from my database and the option selected in the first input will decide the options in the second input.
For example, the two fields are country and state. First, the user selects their country name which will decide the list of states that appear in the state input field. I want the list to change dynamically when user changes the country.
You can do it in PHP submitting a select each time.
For example:
<form action="selectState.php" method="post">
<select name="country">
<option value="countryName">countryName</option>
...
</select>
</form>
then you get the value of $_POST['country'] in selectState.php and print the select the way you want it:
<form action="" method="post">
<select name="state">
<?php
// select use $_POST['country'] to customize the select option's
?>
</select>
</form>
A more user friendly solution (that does not require a new page or refresh) is use AJAX.
So you can use this kind of form:
<form action="selectState.php" method="post">
<select name="country" onchange="ajaxFunction(this.value)">
<option value="countryName">countryName</option>
...
</select>
<select name="state" id="stateList">
<!-- here we'll put the states we want -->
</select>
</form>
With this everytime the user change the select value ajaxFunction() is called and pass to the function the current value selected.
Here is the ajaxFunction (NOTE: this example use jQuery but you can do it in vanilla javascript):
function ajaxFunction(val){
$.ajax({
type: 'post', // choose the method
url: 'page.php', // choose the 'action' page
data: {
country:val // send the data
},
success: function (response) {
// this tell the browser what to do with the response of 'page.php'
// in this case we are telling to put everything we get to the HTML element with stateList id
document.getElementById("stateList").innerHTML=response;
}
});
}
The last thing you need its 'page.php' that simply query the DB (NOTE: this is pseudo code):
<?php
// Query the DB for the states with country = $_POST['country']
while(results){
echo '<option value="results[$i]">results[$i]</option>';
}
?>
Are you using a php framework such as Laravel (recommended) or Codeigniter (not sure if this is still in development).
If so you can construct a 2d php array of countries each with an sub array of its states.
This can be put directly into the rendering page (view).
Using something like
var countries_list =<?php echo json_encode($countries_array); ?>;
will directly inject this into a javascript array which you can use to populate the state select when the country select changes.
Or use ajax but that will be slower and hit the server more.

Jquery OnChange fires but no data returned

I have posted this a few times looking for some help, I cant seem to work out why i dont get any data from my dynamic drop down but i do from the 2 static fields. I did get some answers but mainly saying that i need to sort out the security, which i hope to learn next before anything is live online, everything looks good in Firebug including the trace for the http request, i think its a problem with the query i am trying to run, i will post this again and see if anyone can help me out before i address the security flaws.
Thanks alot for helping me out.
first is html, the subcategory is the problem, all items are stored in a javascript array and works fine, just not the query
<select name="Category" id="Category"
onchange="javascript: dropdownlist(this.options[this.selectedIndex].value);">
<option value="">Select Category</option>
<select name="subcategory" id="subcategory">
<option value="">Select Sub-Category</option>
</select>
<script>
$(function() {
$('#subcategory').change(function() {
$('#subcategory').load('results.php', {value: $(this).val()});
});
});
</script>
$category=$_POST['Category'];
$subcategory=$_POST['Subcategory'];
$destination=$_POST['Destination'];
$result = mysql_query("SELECT * FROM travel WHERE Category='$category'
AND Subcategory='$subcategory' AND Destination='$destination'")
or die(mysql_error());
$row = mysql_fetch_assoc( $result ) ;
echo to table (not posted as is working ok)
Where to even start? Your field name is 'subcategory'. You pass 'value' to results.php and you're attempting to retrieve 'Subcategory' form the $_POST array. You need to line all these names up.
I'm not sure whether the PHP there is the code for results.php or for whatever script the form is posted to, or are they the same? Regardless, whatever results.php needs, you need to include in the data you pass to load. For example, since you currently use 'value', you'd retrieve that via $_POST['value'], not $_POST['Subcategory'].
You only pass to php data from "#subcategory" form, not from "#Category", and with another id than you use in php code. And and you don't have a code for "destination", so I don't know where it should be taken from. Also it's better to put your code in $(document).ready when using jquery. It should be like that:
$(document).ready(function() {
$('#subcategory').change(function() {
$('#subcategory').load('results.php', {Subcategory: $(this).val(), Category: $("#Category").val() });
});
});

simple AJAX dropdown 2

Ok this code seems to be working now (ajax getting the current selection) . But i now have another problem. When i use php $_GET method (for later database search), the output isnt just dropdown chosen word, but also generates another dropdown menu. There is also WAMP error - undefinex index for GET.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#select").change(function(){
$.ajax({
url: "test.php?selected=" +$(this).val(),
success:function(data){
$("#results").html(data);
}
}
)
})
});
</script>
<select id="select">
<option> something </option>
<option> something2 </option>
<option> something3 </option>
</select>
<?php
echo $_GET['selected'];
?>
<div id="results"></div>
<option>
needs to have value
<option value="test">
The problem is arising because you're self-referencing in the ajax call without accounting for the postback. Also the initial page load will throw an undefined index error because the selected key does not exist in the $_GET collection.
At the top of your test.php file:
<?php
if(array_key_exists('selected', $_GET))
{
echo $_GET['selected'];
die();
}
?>
Then remove your echo later on in your example.
Note that this is only to make your example work and show why it failed. Not to give a well-formed example of an AJAX request.
What is echo $_GET['selected']; supposed to display?
Can you give us some PHP code, as well?
And if you have an undefinex index for GET, it means that the array $_GET contains no key named selected. Where do selected come from?
If it comes from the JavaScript you gave us, then it should be select instead. (Also, naming your select with the keyword select is not recommended.)

Autofill form when link is pressed

I have this webpage. It has a page called "services.php". I have several buttons (made of classes), that belong to different "package" prices i offer.
I want the links that say "Select" to autofill a form in another page, or alternativly in a popup form in the page..
I don't really know how to explain it, but as short as possible:
When link is pressed autofill form (in this or other page) with the type of package they chose. Only text autofill
What you seem to be asking is 'loading' a page pre-filled with specific information, you can do this a number of ways, either by utilizing javascript (like jQuery for instance). Or using your PHP, make links that pass variables (say a flag or a reference to pre-fill the fields -- if you want a popup or next page, etc).
Your url would like like the following for the button that a user presses (button would be a simple http link):
http://mywebsite.com/prefill.php?user=bob&package=2
This would have the values bob as the user that requests it (you can reference an id for user info here as well), and package=2 to designate your package options.
Then on the prefill.php page, you would have something that checks for:
$user = $_GET['user'];
$package = $_GET['package'];
Hope that helps
This will populate form fields with whatever you pass to the autoFill() function. This would be a same page example.
<html>
<body>
<form>
<input type="text" id="packageDescription">
<input type="text" id="packagePrice">
</form>
<script>
function autoFill(packageDescription, packagePrice) {
document.getElementById('packageDescription').value = packageDescription;
document.getElementById('packagePrice').value = packagePrice;
}
</script>
Premium Package<br>
Platinum Package
</body>
</html>
You could do something like this:
<select id="packages">
<option value="package1">Package 1</option>
<option value="package2">Package 2</option>
</select>
Submit
When the link is clicked, the following javascript will fire off:
function submitPackage()
{
var package = $("#package").val();
window.open("http://your-site.com/some-script.php?package=" + package);
}
The above will open a pop up window to a page such as this:
http://your-site.com/some-script.php?package=package1
In some-script.php you will do something like this:
You selected the package: <b><?php echo $_GET['package'];?></b>.
Or:
<?php
//Put the packages in an array:
$packages = array();
$packages['package1'] = 'Package 1';
$packages['package2'] = 'Package 2';
//...
?>
<select id="package">
<?php foreach ($packages as $name => $text):?>
<? $selected = ($name == $_GET['package']) ? 'selected' : '';?>
<option value="<? php echo $name;?>" <?php echo $selected;?>>
<?php echo $text;?>
</option>
<? endforeach;?>
</select>
The above will auto select the package they selected in a dropdown box.
if i understood your problem, you want to fill some input fields with information when the user clicks on some links
i can think of 2 ways of doing this : either have the links point to a page like services.php?req=package1 (or any other url you want) and on that page generate the input fields with the information you need (set the default values in the fields with the ones you want), or, use javascript to change the values of the forms without changing the actual page (either via ajax or predefined values)
for javascript you can use the jQuery framework, it has a pretty extensive community of enthusiasts and plenty of examples to get you started with it.
an example for your case would be
$('#btn1').bind('click', function() {
$('#input1').val("value");
$('#input2').val("value2");
});
replace btn1 with the id of the first button or link you have, input1 with the id of the first input in your form, and value with the value you want
I just did this myself. My solution was with jQuery. Just assign an id to your link. The first ID in the code is the link id and the second is the id for the input element you want to populate.
Here is the script:
<script>
$(document).ready(function() {
$('#link_id').click(function() {
$('#input_id').val( $(this).text() ).keyup();
return false;
});
});
</script>
Hope it works!
I've ran several time into the same issue, so I had to write my own script doing this. It's called Autofiller and its pretty simple but does great job.
Here is an example
http://example.com/?autofiller=1&af=1&pof=package&package=package1
So basically it takes several parameters to init the script:
autofiller=1 - init AutoFiller
af=1 - Autofill after page is loaded
pof=package - Find the parent form element of the select with name attribute package. Works also with input form elements.
package=package1 - Will set the select element's value to package1
Hope it helps you! :)

Categories