Finding and replacing PHP Variable value from user drop down box - php

Is it possible in PHP to find and replace a PHP variable with a user defined value from a drop down box on a different PHP page.
Example:
PHP Page 1
$test = '1234';
PHP Page 2
Drop Down Values: (Find and replace $test variable with Drop Down selection)
1
2
3
4
Im have not found much information about this.
The purpose is to pass hexadecimal colours based on user choice.

PHP Variables are server-side variables. You can not change server side variables from client side directly.
Common approaches are: (Although both do same in background)
Using GET to send your data
Using AJAX to dynamically send, fetch and change DOM (Maybe preferred in our case)
On selecting the item on the Drop Down menu, you need to call a method which sends a data to your PHP page and you can change variables.
Your PHP page should handle a GET request change the variable to $test
$test = $_GET["sent_variable"]
While on AJAX, you need to something like:
$.ajax({
url: "your-php-page.php",
type: "POST",
data: { sent_variable: selectedVar}
}).done(function() {
//Something here after doing
});
Read more about AJAX here.
Note: You have to trigger AJAX on selecting drop-down menu. Read about that here.

Assuming the dropdown box is part of a form, you can use the 'post' method.
e.g.
<!--HTML-->
<form method="post" action="myScript.PHP">
<select name="myOption">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" value="GO">
</form>
//myScript.php file
<?PHP
$test = $_POST['myOption'];
echo $test;
?>
I actually have a page on my own site that uses similar functionality for passing hex colours if you want to have a look at the HTML source code http://www.wxls.co.uk/formatmyvba.html

Related

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.

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.

Javascript Value in PHP [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to get the selected option value of a drop down box in PHP code
Drop Down :
<SELECT NAME='action' class="action" id="action" onchange="a();">
<OPTION VALUE="IN"> IN </OPTION>
<OPTION VALUE="OUT"> OUT </OPTION>
</SELECT>
Script to get drop-down text:
<script type="text/javascript">
function a(){
var e = document.getElementById("action");
var strUser = e.options[e.selectedIndex].text;
document.write(strUser);
}
</script>
//got the script from Get selected value in dropdown list using JavaScript?
Here i need to print the value strUser in php. or else on changing the drop down values should print in same page not in new page.
PHP is server-side script run before javascript (client side) code. you can try
Ajax for sending this value to server and generate your desire output.
see detail Ajax
If you want to pass the data selected in the Dropbox to a PHP script, you must use forms or a submit() call from JavaScript over a dynamically generated form.
But if you don't want the page to be reloaded, then you must rely to AJAX technique.
Take a look here and here. There are tons of examples in the net.
< html>
< head>
< script>
//document.getElementById('yourSelectBoxId').options[document.getElementById('yourSelectBoxId').selectedIndex].value//or
function onchg(){
alert(document.getElementById('yourSelectBoxId').value);
}
< /script>
< /head>
< select id="yourSelectBoxId" onchange="onchg();">
< option value=1> a< /option>
< option value=2> b< /option>
< option value=3> c< /option>
< /select>
< body>
< /body>
< /html>
use innerHTML instead of document.write
If you want to pass it to the PHP script (and later save it as a global or in a database) you could use cookies, or submit it as part of a form (what I'd suggest).
So you have
<form action="form_receiver.php" method="get">
Which basically means, submit all the (named) fields in this form to the form_receiver page. The "get" could be replaced by "post" and they are just two methods for sending data ("get" data is encoded in the URL so it can be saved, useful for simple things, and "post" is "sent hidden by the browser" so is better for things like large ammounts of data or confidential stuff).
Now for the data in each field to be sent, you need to give it a name, as you have provided. So for that input field, you would only need to enclose it in a form.
On form_reciever.php, you would be able to access the variables by name using $_GET['name'] or $_POST['name'] depending on which method you used. You could then save it somewhere else to use later.
Cookies should be for preserving data about the user (such as a session id), and I would not recommend using them to pass data between pages. However, if for some reason you require this, you could set cookie data with javascript and get it using $_COOKIE['cookie_name'] in php. If you're setting a cookie in php use setcookie("name", "value") (more details here http://php.net/manual/en/function.setcookie.php).
There are many ways to set cookies in javascript. I would recommend using a library like jQuery and you could set and get cookies in a similar way: $.cookie("name", "new_value") or $.cookie("name") to get the value.

javascript and PHP variable passing

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

Problem with keeping selected value in form after reloading page

I'm trying to populate a second dropdown in a dynamic way based on a previs selected dropdown.
However, I've managed to write get the page to reload when I choose anything in the dropdownbox but the chosen value isnt passed after reloading.
I have register_globals turned off (and prefer to) and i'm using the GET function to submit the form. However when I try setting values in the URL I cant get it to work.
Example: dropdown.php?area=1 still gives me a value in the dropdownbox with the default value.
What am I doing wrong? Running on a LAMP server. Apache 2.2, php 5.3.
Note: I found the php code here on the web wwich is suppose to help me pass the GET variable and select the option in the selectbox.
This is my code:
<html>
<head>
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.area.options[form.area.options.selectedIndex].value;
self.location='dropdown.php?area=' + val ;
}
</script>
</head>
</body>
<? #$area=$HTTP_GET_VARS['area']; ?>
<form action="" method="get">
<select name="area" id="area" onchange="reload(this.form)">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</form>
</body>
</html>
Also, if this could be done with POST (or equivalent function) it would be even better.
Regards.
I think you're not specifying anywhere which one of the options should be selected on page load. Depending on the value of $area, you should add something like
<option selected>1</option>
You could easily do this with a couple of lines of PHP when rendering the option nodes:
<? if $area == 1
print '<option selected>1</option>';
?>
etc.
Alternatively, you could just populate the second combo using client-side javascript eliminating the need for a page reload. If you need to do some sensitive server-side processing to calculate the value of the second combo, do it in a background AJAX call using jQuery (examples here). Postbacks for this kind of thing are kind of undesirable and old-fashioned these days.
Regarding the GET issue, if submitting the form has any side effects (eg. a change in state in the user's account, deleting something, creating a new entity) then it should definitely be a POST. Discussion here for example.

Categories