javascript and PHP variable passing - php

I have two select box and the second select box value is dependent on the first select box. So basically what I am trying to do is that after a user makes a selection on the first select box, it will then store this value of the first select box as a variable. Then it will query my database to populate the second select box, based on the first selected value. Question is, how do I pass in the var I have in the first select box to PHP? I've read other post and people said it's impossible, but if it is then how do people do this? AJAX?

If I understand correctly, then yes, using AJAX is really your only choice.

Indeed, you can, with AJAX, call something like 'getSelectionData.php?data=' + select1.value, which returns a JSON array of data based on the selection in the first select box. You then parse the data and enter it into the second select box.

Add a onchange event listener to the first select box:
document.getElementById("select1").addEventListener("change", function(ev){
var yourstoredvariable = this.value;
someFunctionThatCallsAjax(yourstoredvariable);
}, true);

I assume that you have a Country/City dropdowns, You can do it in two ways, the good AJAX way and the bad way (refresh page on change), I'm gonna describe the good way in jQuery, or at least what I see it good.
this is the client-side (i.e. client) code:
<select id="country">
<option value="1">Canada</option>
<option value="2">UK</option>
</select>
<select id="city" disabled="disabled"></select>
<script type="text/javascript">
$('#country').change(function(){
$('#city').load('/ajax-city.php', {id: $(this).val()});
});
</script>
This is the ajax-city.php code (server):
<?php
$countryId = $_REQUEST['id'];
$cities = array(); // Get it from db, using mysql_query or anything you want to use
foreach($cities as $city) {
echo "<option id=\"{$city['id']}\">{$city['name']}</option>";
}
PS. you would need to include jQuery in your html code, and of course put the two files in the same directory (or change the $.load path).
This particular code is not tested, I've just written it. But it usually works fine to me this way.

You will have an onchange event on the first <select> that will query the server using Ajax with the value of the selected <option> that will return the <option> elements with which to populate the 2nd <select> element.

Question is, how do I pass in the var I have in the first select box to PHP?
I see no problem here.
Just usual, an ordinary html form using GET method.
What's so big about it?

If I see correct you're using Jquery. So you can do this like this:
$('#idOfSelectBox1').change(function(){
jQuery.ajax({
type: "GET",
url:"yourdomain.com/script.php",
data:"selectBox:'"+$('#idOfSelectBox1').val()+"'",
success:function(result){
//do smth with the returned data
}
});
});
in the script.php do your magic and echo what you want to pass back to js

Related

drop down changes from other drop down with calculation. Jscript / Ajax?

I have a Jscript Query.
I have done a bit of reading and found out that AJAX is just a side server for a lfash script that can be used on Linux with php. (please correct me if I have interperated that wrong)
I have no knowledge on how scripts work so this is new, I have tried a couple of different tries but no luck.
I have one drop down box (Box1) (populated from Database)
I have another box (Box2) for a calculation to insert into my database for other uses on ohter parts of hte site.
I need the Box2 to change the figure when someone changes Box1 dropdown before hitting the submit button.
I think because I have the calcualtion this is getting me stuck... Code is as below... Can someone please help me figure out (I think I need some form of Script to do this.) the answer...
Box1
<td><p>selection 1</p>
<select id="t1_type" name="t1_type">
<?php $result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result)){
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>'; } ?>
Box2
<input name="t1_value" id="t1_value" value="
<?php
$var1 = $row_value['t2_value'];
$var2 = $row_dropdown['t1_number'];
$total = round ($var2 * $var1);
echo "" . $total . "";
?>" />
I hope this is all the code you need, (Let me know if more required)
What it needs to do is show new calculation whenever someone changes the box1 option BEFORE the submit button is clicked, so it submits the correct calculation to the database for future use.
I think it would need pretty much "t2_value" from box2 to change when ever "t2_name changed from box1.
And once again the best link to learn about the solution. (Learnt about Joins now from my last question!! Almost a intermediate user. ;-) )
Edit :
I saw that your second box was a textbox I believe, if thats the problem then you should do something like this
<select id="t1_type" name="t1_type" onchange="change(this);">
<?php
$result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result))
{
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>';
}
?>
</select>
This defines your <select> box like you did in your question.
Add an onChange event into your first <select> and then create a function to handle to onChange event. An onChange event fires whenever the user changes the item in the <select> element.
Javascript :
( put this part of the code above the </head> )
<script language="javascript" type="text/javascript">
function change(element)
{
// do here whatever you want
// you can change the value of the <input> box with :
// document.getElementById(element.id).value = your_value
// If you want to see if this part works, then try adding this :
// alert("It works!");
// If you want to get the text of the item which has been selected in Box1 use :
// $("#t1_type option:selected").text();
}
</script>
Note: because PHP is server side, you can't update your Box2 dynamically without a page refresh, Javascript however is Client Side and CAN do this.
Note : the $("#t1_type option:selected").text(); code requires you to include the jQuery library into your script. Be sure to convert this variable to a float, int or double if you want to calculate with it, else the outcome will give NaN (Not a Number)
Tutorial on including jQuery Libary :
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
If you're new to JavaScript, you should try some tutorials. The ones at w3Schools.com helpt me alot, but some people say they're not always correct, but anyhow, read some stuff about Javascript to actually know what you are doing, instead of copypasting code :)

Fill Single Input Based On Prior Select - MYSQL PHP JS?

I want to grab my customers phone number from a MYSQL database and auto populate it into an input box based on users selection of customers in a prior dropdown box.
I've managed to do this in the past when filling in larger amounts of data but what I've previously used seems like a lot of code to auto fill a single input box.
I know how to fill the customer phone based on the data passed from the prior page (although I've deleted that bit here) but I want that data to change dynamically as users use the dropdown.
There's got to be an easy way to do this but I'm a complete newb at js (and only barely proficient at PHP & MYSQL). Can anyone give me a hand?
My PHP/HTML:
$result = mysql_query("SELECT cust_id, name, phone FROM customers ORDER BY name ASC");
$customers = mysql_fetch_array($result);
<label for="customer">Customer:</label>
<select name="customer">
<option value="0">Add New Customer</option>
<? foreach ($customers as $customer): ?>
<option value="<?=$customer['cust_id']?>" <?=($customer['cust_id'] == $parts['cust']) ? "selected" : ""?>><?=$customer['name']?></option>
<? endforeach; ?>
</select>
<label for="custphone">Customer Phone:</label>
<input type="text" name="custphone" value="">
Let me know if you need anything else from me and thanks in advance for helping me out on this.
For this answer, I will use the jQuery syntax, jQuery is a free javascript library, and you'll certainly use it in the future, read more.
To resume, we'll use an event triggered by your select element, when his value is changed, we'll process an AJAX request with some parameters to a PHP page (ajax.php) which returns the phone number of the customer previously choosen.
First you need to include in your HTML web page, the jQuery script, with the <script> tag.
<script src="path/to/jquery.js"></script>
In a second time, we'll create a new javascript script (assuming you add some id's to your HTML elements):
<script type="text/javascript">
$(document).ready(function(){ // When the document is ready
$("select#customers").on("change",function(){ // We attach the event onchange to the select element
var customer_id = this.value; // We retirve the customer's id
$.ajax({
url : "path/to/ajax.php", // path to you php file which returns the phone number
method : "post", // We want a POST request
data : "customer_id="+customer_id, // You'll retrieve this data in your $_POST variable in ajax.php : $_POST['customer_id']
success: function(response) { // The function to execute if the request is a -success-, response will be the customer phone number
$("input#custphone").value(response); // Fill the phone number input
}
});
});
});
</script>
Now, you've all the gear to continue, you should read about jQuery and AJAX.
You just have to create the "ajax.php", retrieve your customer id with the $_POST variable, process the SQL query to retrieve the phone number, then, return it with an echo.
Sounds like you want to look into AJAX. jQuery.ajax() makes it pretty easy.
Basically, you have a page on the server that queries the database and returns a JSON encoded string that the javascript can convert (using jQuery.parseJSON)back into an array and populate the list!
Use .change() to bind an event to the dropdown's change event. This will fire whenever the selection changes. Inside, you want to get the value (see demo on that page) and send an AJAX request to the server.
The PHP script on the server will query the database and return a JSON string. In the success function of the jQuery AJAX block you can populate the new list with the decoded information. See this page for a tutorial on how to add items to a select.

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() });
});
});

How do you set the default value of a drop down list that is being called via AJAX from another page?

For my code, my drop down lists are initiated on the original page, via
<select name =country id=country
onchange=showRecords(this.value,'country','province')>"
This function is taking the value, equating it to country, then querying MySQL, and setting the results where id=province, and creating cascading dropdown lists. This is obviously via Ajax.
So, when $_REQUEST['province'] is set, then the Province dropdown list gets populated with all provinces from the country to which it belongs, etc.; i.e.;
<?if(isset($province)){
echo "<script>showRecords('".$country."','country','province');</script>";}?>
However, for the life of me, I cannot figure out how I can set the default value equal to $_REQUEST['province']. I cannot use the traditional way:
if (($selected) == ($value)) {
$options.= " selected";
}
Because it is querying the AJAX page with one piece of information at a time.
Any ideas would be greatly appreciated.
Your code doesn't seem to make a lot of sense. The particular thing that worries me is that you say ajax is loading one item at a time?
Perhaps something like this. A country select tag like...
<select onchange="showRecords(this)">
As well as creating the javascript function showRecords() which will be called when someone chooses an option in the select tag.
<script>
function showRecords(calling_element) {
// do AJAX call here using calling_element.options[calling_element.selectedIndex].value as the selected country. this.value does not work for select tags.
}
</script>
the PHP page that receives this AJAXed request would reply with a JSON object containing all of the province values, or a delimited list.
once the Javascript showRecords function receives the responce from the PHP page, it would add each of these options to the correct select tag. Once finished, it would set the default value to whichever option it wants by something like the following:
target_element.selectedIndex = {desired list index here};
I have a lot of assumptions to your questions,
first is, if bydefault you have the select province like this
<select id="province">
<option value=""></option>
<option value="California">California</option>
<option value="Washington">Washingthon</option>
</select>
then you can use this script to default select
document.getElementById("province").value="Washington";
but if bydefault you have the select province like this
<select id="province"></select>
then you can use this script to default select
document.getElementById("province").innerHTML='<option value="Wahsington">Washington</option>';
so it depend on your code and your need. maybe if you have another case the problem should be solved in another way.
cmmiiw :)

AJAX Controlled Multiple Select Box Strategy

I've done some reading on AJAX, and would like to create a listbox, that controls what is displayed in a separate textbox located within the same form. The backend of the website is handled in php, and the possible values and whatnot is stored within the MySQL database via php. What's the best way of obtaining the listbox values as well as the textbox values, and if your answer is JS, how do I create multiple selects in JS?
Well this is really a wide theme question.
My approach would be to create a listbox with php and put an onchange event that will call an ajax with value parameter, that ajax call will fill textbox.
You should use jquery, read some documentation here http://docs.jquery.com/Main_Page
multiple select listbox
<select id="choices" multiple="multiple" .. >
If you were using jQuery you could do something like:
$("#choices").change(function() {
var choices = {};
$("#choices option:selected").each(function() {
choices[this.id] = $(this).val();
});
$.post("http://example.com/choice_handler.php", choices, function(content) {
$("#textarea").val(content);
});
});
choice___handler.php would look at $_POST to retrieve the id/value pairs and produce content that would be returned and then assgned as the value of a textarea.
Note: i haven't tested/debugged any of this - just some code sketching here

Categories